Why pass textInput content to string into ArrayList - android

I want pass values from a form making with TextInputLayout but Android Studio detects my content as INT.
I put the complete class of my activity as well as the view in .xml to determine the problem
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import com.prosegma.rso.R;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class AccionActivity extends AppCompatActivity {
ImageView imageView;
private Context activity;
private String[]header={"Campo","Respuesta"};
private String shortText="RSO PROSEGMA";
private String longText="Eliminamos Riesgos Sumamos Valor";
private AccionPdf accionPdf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accion);
Button btnCamera1 = (Button)findViewById(R.id.BtnCamera1);
imageView = (ImageView)findViewById(R.id.reporte1);
btnCamera1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,0);
}
});
Date date = new Date();
String timeStamp = new SimpleDateFormat("dd/MM/yyyy").format(date);
accionPdf=new AccionPdf(getApplicationContext());
accionPdf.openDocument();
accionPdf.addMetaData("Reporte","Acción Insegura","www.prosegma.com");
accionPdf.addTitle("Reporte Acción Insegura","RSO Prosegma"," " +timeStamp);
accionPdf.addParagraph(shortText);
accionPdf.addParagraph(longText);
accionPdf.createTable(header,getClients());
accionPdf.closeDocument();
}
TextInputEditText Nreport = (TextInputEditText) findViewById(R.id.nReporta);
private ArrayList<String[]>getClients(){
ArrayList<String[]>rows=new ArrayList<>();
rows.add(new String[]{"Nombre de quien reporta", Nreport });
rows.add(new String[]{"Nombre del trabajador","No"});
rows.add(new String[]{"Empresa contratista","ju"});
rows.add(new String[]{"Medidas Necesarias","hu"});
return rows;
}
public void pdfAccion(View view)
{
accionPdf.verReporteAccion();
}
public void enviarA(View view) {
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, "receiver_email_address");
email.putExtra(Intent.EXTRA_SUBJECT, "subject");
email.putExtra(Intent.EXTRA_TEXT, "email body");
Uri uri = Uri.fromFile(new File(android.os.Environment.getExternalStorageDirectory(), "pdfFileName"));
email.putExtra(Intent.EXTRA_STREAM, uri);
email.setType("application/pdf");
email.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getActivity().startActivity(email);
}
public Context getActivity() {
return activity;
}
}
I update the publication with the activity, I have tried to change the InputTextLayout by EditText but the situation is the same, it throws me an incompatibility error.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<include layout="#layout/actionbar_toolbar"/>
<ScrollView
android:id="#+id/reportes0"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
>
<LinearLayout
android:id="#+id/reportes1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="#dimen/activity_vertical_margin"
android:orientation="vertical"
android:weightSum="10"
>
<View
android:layout_width="match_parent"
android:layout_height="7dp"
/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray"
/>
<View
android:layout_width="match_parent"
android:layout_height="7dp"
/>
<ImageView
android:id="#+id/reporte1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/BtnCamera1"
android:layout_weight="1"
android:layout_height="64sp"
android:layout_width="64sp"
android:background="#drawable/camera"
android:gravity="center"
/>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/EditTextBlack"
android:layout_marginTop="4dp"
>
<android.support.design.widget.TextInputEditText
android:id="#+id/nReporta"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:hint="NOMBRE DE QUIEN REPORTA"
/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/EditTextBlack"
android:layout_marginTop="4dp"
>
<android.support.design.widget.TextInputEditText
android:id="#+id/nTrabajador"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="NOMBRE DEL TRABAJADOR"
/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/EditTextBlack"
android:layout_marginTop="4dp"
>
<android.support.design.widget.TextInputEditText
android:id="#+id/eContratista"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="EMPRESA CONTRATISTA"
/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/EditTextBlack"
android:layout_marginTop="4dp"
>
<android.support.design.widget.TextInputEditText
android:id="#+id/aMedidas"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="14sp"
android:hint="ACCIÓN, MEDIDAS CORRECTIVAS INMEDIATAS"
android:inputType="textShortMessage"
/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/EditTextBlack"
android:layout_marginTop="4dp"
>
</android.support.design.widget.TextInputLayout>
<CheckBox
android:id="#+id/checkAccidente"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ACCIDENTE" />
<CheckBox
android:id="#+id/checkImpacto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="IMPACTO AMBIENTAL" />
<CheckBox
android:id="#+id/checkEnfermedad"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ENFERMEDAR PROFESIONAL" />
<CheckBox
android:id="#+id/checkReincidente"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="REINCIDENTE" />
<CheckBox
android:id="#+id/checkSancion"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="¿APLICA SANCIÓN?"
/>
<Button
android:id="#+id/guardarAccion"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="GUARDAR REPORTE"
android:theme="#style/RaisedButtonDark"
android:onClick="pdfAccion"
/>
</LinearLayout>
</ScrollView>
</android.support.design.widget.CoordinatorLayout>

TextInputEditText Nreport = (TextInputEditText) findViewById(R.id.nReporta);
this line is outside OnCreate(Bundle savedInstanceState) method. Thats why it throws null. It should be like this
public class MainActivity extends AppCompatActivity {
TextInputEditText Nreport;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Button btnCamera1 = (Button)findViewById(R.id.BtnCamera1);
// imageView = (ImageView)findViewById(R.id.reporte1);
Date date = new Date();
String timeStamp = new SimpleDateFormat("dd/MM/yyyy").format(date);
Nreport = (TextInputEditText) findViewById(R.id.nReporta);
getClients();
}
private ArrayList<String[]> getClients(){
ArrayList<String[]>rows=new ArrayList<>();
rows.add(new String[]{"Nombre de quien reporta", Nreport.getText().toString() }); // get text like this
rows.add(new String[]{"Nombre del trabajador","No"});
rows.add(new String[]{"Empresa contratista","ju"});
rows.add(new String[]{"Medidas Necesarias","hu"});
return rows;
}

Related

How to move from child layout to parent layout with losing data on parent layout? And How can I optimize my code?

I am new to android development.
Following is the code to my android app called "My Fruit List" in which Main Activity shows chosen fruits in "Text Views" arranged in "Linear Layout (vertical orientation)" inside "Scroll Views" that are selected from the second layout by using the "ADD A FRUIT" button at the bottom of the current Main Layout. This program functions as expected but I have two questions:
My first question is that as I have made the Main Activity as the parent activity for the second layout that's working as a child activity. But when I move from child to parent using the left arrow at the top left all the data from Main Activity's Text Views are vanished. I have overridden onSaveInstance and onRestoreInstance for keeping the main activity's data when screen's rotated but when I move from child to parent using the top left arrow it vanishes all the data present in those "Text Views". Why?
My second question is that how can I optimize my code means by making it more shorter and clearer?
Much Thanks!
MainActivity.java:
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "MainActivity";
private Button button_addItem;
private TextView item1;
private TextView item2;
private TextView item3;
private TextView item4;
private TextView item5;
private TextView item6;
private TextView item7;
private TextView item8;
private TextView item9;
private TextView item10;
private static final int CHOSEN_FRUIT = 1;
//string keys for onSaveInstance and onRestoreInstance
private static final String ITEM_1_KEY = "item1key";
private static final String ITEM_2_KEY = "item2key";
private static final String ITEM_3_KEY = "item3key";
private static final String ITEM_4_KEY = "item4key";
private static final String ITEM_5_KEY = "item5key";
private static final String ITEM_6_KEY = "item6key";
private static final String ITEM_7_KEY = "item7key";
private static final String ITEM_8_KEY = "item8key";
private static final String ITEM_9_KEY = "item9key";
private static final String ITEM_10_KEY = "item10key";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_addItem = findViewById(R.id.button_addItem);
item1 = findViewById(R.id.textView_item1);
item2 = findViewById(R.id.textView_item2);
item3 = findViewById(R.id.textView_item3);
item4 = findViewById(R.id.textView_item4);
item5 = findViewById(R.id.textView_item5);
item6 = findViewById(R.id.textView_item6);
item7 = findViewById(R.id.textView_item7);
item8 = findViewById(R.id.textView_item8);
item9 = findViewById(R.id.textView_item9);
item10 = findViewById(R.id.textView_item10);
button_addItem.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AvailableItems.class);
startActivityForResult(intent, CHOSEN_FRUIT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CHOSEN_FRUIT) {
if (resultCode == RESULT_OK) {
if (item1.getText().toString().equalsIgnoreCase("empty"))
item1.setText(data.getStringExtra(AvailableItems.FRUIT_ID));
else if (item2.getText().toString().equalsIgnoreCase("empty"))
item2.setText(data.getStringExtra(AvailableItems.FRUIT_ID));
else if (item3.getText().toString().equalsIgnoreCase("empty"))
item3.setText(data.getStringExtra(AvailableItems.FRUIT_ID));
else if (item4.getText().toString().equalsIgnoreCase("empty"))
item4.setText(data.getStringExtra(AvailableItems.FRUIT_ID));
else if (item5.getText().toString().equalsIgnoreCase("empty"))
item5.setText(data.getStringExtra(AvailableItems.FRUIT_ID));
else if (item6.getText().toString().equalsIgnoreCase("empty"))
item6.setText(data.getStringExtra(AvailableItems.FRUIT_ID));
else if (item7.getText().toString().equalsIgnoreCase("empty"))
item7.setText(data.getStringExtra(AvailableItems.FRUIT_ID));
else if (item8.getText().toString().equalsIgnoreCase("empty"))
item8.setText(data.getStringExtra(AvailableItems.FRUIT_ID));
else if (item9.getText().toString().equalsIgnoreCase("empty"))
item9.setText(data.getStringExtra(AvailableItems.FRUIT_ID));
else if (item10.getText().toString().equalsIgnoreCase("empty"))
item10.setText(data.getStringExtra(AvailableItems.FRUIT_ID));
else
Toast.makeText(this, "List is full!", Toast.LENGTH_SHORT).show();
// Log.d("TESTMESSAGE", "onActivityResult: " + data.getStringExtra(AvailableItems.FRUIT_ID));
}
}
}
#Override
protected void onSaveInstanceState(#NonNull Bundle outState) {
outState.putString(ITEM_1_KEY, item1.getText().toString());
outState.putString(ITEM_2_KEY, item2.getText().toString());
outState.putString(ITEM_3_KEY, item3.getText().toString());
outState.putString(ITEM_4_KEY, item4.getText().toString());
outState.putString(ITEM_5_KEY, item5.getText().toString());
outState.putString(ITEM_6_KEY, item6.getText().toString());
outState.putString(ITEM_7_KEY, item7.getText().toString());
outState.putString(ITEM_8_KEY, item8.getText().toString());
outState.putString(ITEM_9_KEY, item9.getText().toString());
outState.putString(ITEM_10_KEY, item10.getText().toString());
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(#NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
item1.setText(savedInstanceState.get(ITEM_1_KEY).toString());
item2.setText(savedInstanceState.get(ITEM_2_KEY).toString());
item3.setText(savedInstanceState.get(ITEM_3_KEY).toString());
item4.setText(savedInstanceState.get(ITEM_4_KEY).toString());
item5.setText(savedInstanceState.get(ITEM_5_KEY).toString());
item6.setText(savedInstanceState.get(ITEM_6_KEY).toString());
item7.setText(savedInstanceState.get(ITEM_7_KEY).toString());
item8.setText(savedInstanceState.get(ITEM_8_KEY).toString());
item9.setText(savedInstanceState.get(ITEM_9_KEY).toString());
item10.setText(savedInstanceState.get(ITEM_10_KEY).toString());
}}
AvailableItems (SecondActivity):
package com.xafak.fruitshoppinglist;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class AvailableItems extends AppCompatActivity {
private Button bananaImage;
private Button grapeImage;
private Button appleImage;
private Button watermelonImage;
private Button pineappleImage;
private Button avocadoImage;
private Button cherryImage;
private Button cirtusImage;
private Button strawberryImage;
private Button pomegranateImage;
public static final String FRUIT_ID = "fruit_id";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_available_items);
bananaImage = findViewById(R.id.bananas);
grapeImage = findViewById(R.id.grapes);
appleImage = findViewById(R.id.apple);
watermelonImage = findViewById(R.id.watermelon);
pineappleImage = findViewById(R.id.pineapple);
avocadoImage = findViewById(R.id.avocado);
cherryImage = findViewById(R.id.cherry);
cirtusImage = findViewById(R.id.citrus);
strawberryImage = findViewById(R.id.strawberry);
pomegranateImage = findViewById(R.id.pomegranate);
}
public void addItemToList(View v) {
switch (v.getId()) {
case R.id.bananas:
configureIntent("Bananas");
break;
case R.id.grapes:
configureIntent("Grapes");
break;
case R.id.apple:
configureIntent("Apple");
break;
case R.id.watermelon:
configureIntent("Watermelon");
break;
case R.id.pineapple:
configureIntent("Pineapple");
break;
case R.id.avocado:
configureIntent("Avocado");
break;
case R.id.cherry:
configureIntent("Cherry");
break;
case R.id.citrus:
configureIntent("Citrus");
break;
case R.id.strawberry:
configureIntent("Strawberry");
break;
case R.id.pomegranate:
configureIntent("Pomegranate");
break;
default:
}
}
public void configureIntent(String fruitName) {
Intent replyIntent = new Intent();
replyIntent.putExtra(FRUIT_ID, fruitName);
setResult(RESULT_OK, replyIntent);
finish();
} }
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.xafak.fruitshoppinglist">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".AvailableItems"
android:label="Available Fruits"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity" />
</activity>
</application>
</manifest>
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ScrollView
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="16dp"
android:layout_marginBottom="8dp"
android:foregroundGravity="center_vertical|clip_horizontal|center"
app:layout_constraintBottom_toTopOf="#+id/button_addItem"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView2">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/textView_item1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="#string/empty"
android:textSize="45sp" />
<TextView
android:id="#+id/textView_item2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="#string/empty"
android:textSize="45sp" />
<TextView
android:id="#+id/textView_item3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="#string/empty"
android:textSize="45sp" />
<TextView
android:id="#+id/textView_item4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="#string/empty"
android:textSize="45sp" />
<TextView
android:id="#+id/textView_item5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="#string/empty"
android:textSize="45sp" />
<TextView
android:id="#+id/textView_item6"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="#string/empty"
android:textSize="45sp" />
<TextView
android:id="#+id/textView_item7"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="#string/empty"
android:textSize="45sp" />
<TextView
android:id="#+id/textView_item8"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="#string/empty"
android:textSize="45sp" />
<TextView
android:id="#+id/textView_item9"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="#string/empty"
android:textSize="45sp" />
<TextView
android:id="#+id/textView_item10"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="#string/empty"
android:textSize="45sp" />
</LinearLayout>
</ScrollView>
<Button
android:id="#+id/button_addItem"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:text="#string/select_fruit"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="213dp"
android:layout_height="61dp"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/shoppingcart" />
</androidx.constraintlayout.widget.ConstraintLayout>
activity_available_items.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AvailableItems">
<LinearLayout
android:layout_width="0dp"
android:layout_height="0dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/guideline2"
app:layout_constraintHorizontal_bias="0.39"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/guideline3">
<Button
android:id="#+id/bananas"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="addItemToList"
android:text="#string/bananas"
android:textSize="20sp" />
<Button
android:id="#+id/apple"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="addItemToList"
android:text="#string/apple"
android:textSize="20sp" />
<Button
android:id="#+id/avocado"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="addItemToList"
android:text="#string/avocado"
android:textSize="20sp" />
<Button
android:id="#+id/cherry"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="addItemToList"
android:text="#string/cherry"
android:textSize="20sp" />
<Button
android:id="#+id/citrus"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="addItemToList"
android:text="#string/citrus"
android:textSize="20sp" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="0dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="#+id/guideline2"
app:layout_constraintTop_toTopOf="#+id/guideline3">
<Button
android:id="#+id/grapes"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="addItemToList"
android:text="#string/grapes"
android:textSize="20sp" />
<Button
android:id="#+id/pineapple"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="addItemToList"
android:text="#string/pineapple"
android:textSize="20sp" />
<Button
android:id="#+id/pomegranate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="addItemToList"
android:text="#string/pomegranate"
android:textSize="20sp" />
<Button
android:id="#+id/strawberry"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="addItemToList"
android:text="#string/strawberry"
android:textSize="20sp" />
<Button
android:id="#+id/watermelon"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="addItemToList"
android:text="#string/watermelon"
android:textSize="20sp" />
</LinearLayout>
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline2"
android:layout_width="50dp"
android:layout_height="50dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintGuide_percent="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline3"
android:layout_width="0dp"
android:layout_height="0dp"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintGuide_percent="0.3"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/imageView"
android:layout_width="583dp"
android:layout_height="97dp"
android:contentDescription="#string/fruit_image"
app:layout_constraintBottom_toTopOf="#+id/guideline3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/fruitmarket" />
</androidx.constraintlayout.widget.ConstraintLayout>
There is no Need for onSaveInstanceState or onRestoreState.
use an arraylist, which holds the Strings for your TextViews.
private ArrayList<String> arraylist = ArrayList<String>();
This will make sure, that at the beginning you have an empty arraylist.
In OnActivityResult you add the new received String to the arraylist.
if (requestCode == CHOSEN_FRUIT) {
if (resultCode == RESULT_OK) {
arraylist.add(data.getStringExtra(AvailableItems.FRUIT_ID));
}
}
finally you use the Strings in onResume to fill your TextViews with data.
if(arraylist.size==1){
TextView1.setText(arraylist[0];
}
if(arraylist.size==2){
TextView2.setText(arraylist[1];
}
.
.
.
Even when your device is rotated the data inside your ArrayList should be kept and the TextViews gets filled with data in onResume.
This is not the most elegant way to make a list, as it does not increase dynamically in size, but for a dynamic increase in size you could implement a recyclerview for example.

Android Initial Login Screen then use fragments to swipe between screens once login is successful

I am trying to create an Android app, then has an initial login screen that detects if a user is Admin or User. Once logged in, the user (depending on their role) will see different tabs to swipe between. I have a basic app that starts with a login activity and the login to decipher the users roles (using static values for now). First part is ok. Now when I try to use Fragments after the login screen, I'm getting stuck.
I have a LoginActivity that has an onClikcListener on a button after user enters credentials. Depending on whether the user is Amin or General Users, it will just to a new activity either activity_vote_admin or activity_vote_user. At this point I am stuck. Any ideas if what I am trying to do is valid. Or is there a better way to do this. At the moment I am getting this error.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.confidencevotefragmentrebuild/com.example.confidencevotefragmentrebuild.activity_vote_admin}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference.
LoginActivity (this is my main activity)
...
package com.example.confidencevotefragmentrebuild;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LoginActivity extends AppCompatActivity {
private static EditText username;
private static EditText password;
public static TextView attempts;
private static Button submit_button;
int attempt_counter = 5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginButton();
}
public void loginButton() {
username = (EditText) findViewById(R.id.editText);
password = (EditText) findViewById(R.id.editText2);
attempts = (TextView) findViewById(R.id.textView_Attempts);
//Reference button view
final Button submit_button = findViewById(R.id.submit_button);
// perform click event on button
submit_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (username.getText().toString().equals("admin") &&
password.getText().toString().equals("pass")) {
Toast.makeText(LoginActivity.this, "Welcome " + username.getText(),
Toast.LENGTH_SHORT).show();
Intent intent = new Intent(LoginActivity.this, activity_vote_admin.class);
startActivity(intent);
} else if (username.getText().toString().equals("user") &&
password.getText().toString().equals("pass")) {
Toast.makeText(LoginActivity.this, "Welcome " + username.getText(),
Toast.LENGTH_SHORT).show();
Intent intentUser = new Intent(LoginActivity.this, activity_vote_user.class);
startActivity(intentUser);
} else {
Toast.makeText(LoginActivity.this, "User or Password incorrect",
Toast.LENGTH_SHORT).show();
attempt_counter--;
attempts.setText(Integer.toString(attempt_counter));
if (attempt_counter == 0) {
Toast.makeText(LoginActivity.this, "Too many failed attempts, please close app and try again",
Toast.LENGTH_SHORT).show();
submit_button.setEnabled(false);
}
}
}
}
);
}
}
...
Activity_vote_admin
...
package com.example.confidencevotefragmentrebuild;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
public class activity_vote_admin extends AppCompatActivity {
/**
* Field for selecting the number of confidence votes
*/
RatingBar mResults;
private RatingBar rBar;
Button mBtn;
/**
* Spinner field to enter the project name
*/
private Spinner mProjectSpinner;
/**
* Projects. The possible values are:
* stored locally - Needs to get values from a database. TODO
*/
int mProject = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vote_main_admin);
// Find the view pager that will allow the user to swipe between fragments
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
// Create an adapter that knows which fragment should be shown on each page
AdminFragmentPagerAdapter adapter = new AdminFragmentPagerAdapter(getSupportFragmentManager());
// Set the adapter onto the view pager
viewPager.setAdapter(adapter);
// initiate a rating bar
rBar = findViewById(R.id.rating_bar);
//float vote = rBar.getRating();
// Find all relevant views for user input
mResults = findViewById(R.id.rating_bar);
mProjectSpinner = findViewById(R.id.spinner_project);
// Run getRating method to get rating number from a rating bar
//getRating();
// Initiate button
mBtn = findViewById(R.id.voteButton);
// perform click event on button
mBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// get values and then displayed in a toast
//String totalStars = "Total Stars:: " + RatingBar.getNumStars();
float vote = rBar.getRating();
String rating = "Rating : " + vote;
Toast.makeText(getApplicationContext(), rating + "\n", Toast.LENGTH_LONG).show();
}
});
projectSpinner();
}
// Setup the dropdown spinner that allows the user to select the role.
private void projectSpinner() {
// Create adapter for spinner. The list options are from the String array it will use
// the spinner will use the default layout
ArrayAdapter projectSpinnerAdapter = ArrayAdapter.createFromResource(this,
R.array.projects, android.R.layout.simple_spinner_item);
// Specify dropdown layout style - simple list view with 1 item per line
projectSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
// Apply the adapter to the project spinner
mProjectSpinner.setAdapter(projectSpinnerAdapter);
// Set the integer mSelected to the constant values
mProjectSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
if(mProjectSpinner.getSelectedItem() == "This is Hint Text");
if (!TextUtils.isEmpty(selection)) {
if (selection.equals(getString(R.string.nextGEMS1_5))) {
mProject = 0 ;
return;
} else if (selection.equals(getString(R.string.nextGEMS1_6))) {
mProject = 1;
return;
} else if (selection.equals(getString(R.string.nextGEMS1_7))) {
mProject = 2;
return;
} else if (selection.equals(getString(R.string.nextGEMS1_8))) {
mProject = 3;
return;
} else if (selection.equals(getString(R.string.nextGEMS1_9))) {
mProject = 4;
return;
}
else mProject = 0;
}
}
// Because AdapterView is an abstract class, onNothingSelected must be defined
#Override
public void onNothingSelected(AdapterView<?> parent) {
mProject = 0; // User
}
});
}
}
...
activity_vote_main_admin.xml
...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.viewpager.widget.ViewPager
android:name="com.example.confidencevotefragmentrebuild.testFragment1"
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
...
activity_login.xml
...
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".LoginActivity"
tools:showIn="#layout/activity_login">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#5fb0c9"
android:orientation="vertical"
android:scrollbarAlwaysDrawVerticalTrack="true">
<TextView
android:id="#+id/login_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginTop="16dp"
android:gravity="center_horizontal"
android:text="LOGIN"
android:textColor="#fff"
android:textSize="20sp"
android:textStyle="bold" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="500dp"
android:background="#ffffff"
android:elevation="4dp"
android:orientation="vertical"
android:padding="20dp"
android:layout_below="#+id/login_title"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="80dp">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="450dp"
android:orientation="vertical"
android:paddingTop="30dp">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="70dp">
<EditText
android:id="#+id/editText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:drawableLeft="#drawable/usericon"
android:hint="User Name"
android:inputType="textEmailAddress"
android:maxLines="1" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/editText2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:drawableLeft="#drawable/lock"
android:hint="Password"
android:inputType="textPassword"
android:maxLines="1" />
</com.google.android.material.textfield.TextInputLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:paddingTop="5dp"
android:text="Forgot Password?" />
<Button
android:id="#+id/submit_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="22dp"
android:background="#drawable/action_buttom"
android:text="Sign in"
android:textAllCaps="false"
android:textColor="#fff"
android:textSize="18sp" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="20dp"
android:orientation="horizontal"
android:paddingTop="1dp">
<TextView
android:id="#+id/attempts_text"
android:layout_width="wrap_content"
android:layout_height="25dp"
android:layout_gravity="center_horizontal"
android:paddingTop="1dp"
android:text="Number of attempts remaining: " />
<TextView
android:id="#+id/textView_Attempts"
android:layout_width="match_parent"
android:layout_height="25dp"
android:layout_gravity="center_horizontal"
android:paddingTop="1dp"
android:text="5" />
</LinearLayout>
<TextView
android:id="#+id/lnkRegister"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="1dp"
android:gravity="center"
android:paddingTop="30dp"
android:text="Register here"
android:textColor="#5fb0c9"
android:textSize="16sp" />
</LinearLayout>
</RelativeLayout>
<ImageButton
android:id="#+id/conferencevote_logo"
android:layout_width="210dp"
android:layout_height="180dp"
android:layout_below="#+id/login_title"
android:layout_centerHorizontal="true"
android:layout_marginTop="2dp"
android:elevation="4dp"
android:background="#drawable/rounded_button"
android:src="#drawable/confvotenew"
/>
</RelativeLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
...
AdminFragemntyPagerAdapter
...
package com.example.confidencevotefragmentrebuild;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
public class AdminFragmentPagerAdapter extends FragmentPagerAdapter {
public AdminFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
return new testFragment1();
} else if (position == 1) {
return new testFragment2();
} else {
return new testFragment2();
}
}
#Override
public int getCount() {
return 3;
}
}
...
aactivity_vote_user.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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#5fb0c9"
android:orientation="vertical"
android:scrollbarAlwaysDrawVerticalTrack="true">
<TextView
android:id="#+id/vote_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginTop="16dp"
android:gravity="center_horizontal"
android:text="USER VOTE"
android:textColor="#fff"
android:textSize="20sp"
android:textStyle="bold"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="500dp"
android:background="#ffffff"
android:elevation="4dp"
android:orientation="vertical"
android:padding="20dp"
android:layout_below="#+id/vote_title"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="80dp">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="450dp"
android:orientation="vertical"
android:paddingTop="70dp">
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp">
<Spinner
android:id="#+id/spinner_project"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="25dp"
android:layout_marginRight="25dp"
android:hint="#string/spinner_hint"
android:maxLines="1"
android:singleLine="true"
android:backgroundTint="#color/attCobalt"
android:popupBackground="#color/myBlue"
android:dropDownSelector="#color/attBlue"
/>
</com.google.android.material.textfield.TextInputLayout
>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<RatingBar
android:id="#+id/rating_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:stepSize="1.0"
android:layout_marginTop="40dp"
android:theme="#style/rating_bar"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingTop="5dp"
android:text="Vote and Submit" />
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</com.google.android.material.textfield.TextInputLayout>
<Button
android:id="#+id/voteButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="22dp"
android:background="#drawable/action_buttom"
android:text="Submit"
android:textAllCaps="false"
android:textColor="#fff"
android:textSize="18sp" />
/>
</LinearLayout>
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
<ImageButton
android:id="#+id/conferencevote_logo"
android:layout_width="210dp"
android:layout_height="180dp"
android:layout_below="#+id/login_title"
android:layout_centerHorizontal="true"
android:layout_marginTop="55dp"
android:elevation="4dp"
android:background="#drawable/rounded_button"
android:src="#drawable/confvotenew"
/>
</RelativeLayout>
...
My fragments are as follows.
...
package com.example.confidencevotefragmentrebuild;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
public class testFragment1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_vote_user, container, false);
}
}
...
There are two reason for this issue :
You didn't declare any button on "activity_vote_main_admin.xml", thats why your view not binding with activity and giving null pointer exception.
May be you declare the button on fragment xml and trying to bind it with activity.

I'm having trouble with phone number authentication. Verify_otp generates a unique code for any verified number

I'm having trouble with phone number authentication. Verify_otp generates a unique code for any verified number. But the biggest problem is that it only generates the code if the numbers start with 6599 ..... a number 6598 .... it no longer generates the code.
I can not find an outlet for him to accept any phone number.
this is a part of the RegistrationModel.java file
public static class OTP_Details{
/**
* status : 2
* message : Otp Sent to phone for Verification
* otp : 2017
* auto_otp : 1
*/
private int status;
private String message;
private String otp;
private int auto_otp;
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getOtp() {
return otp;
}
public void setOtp(String otp) {
this.otp = otp;
}
public int getAuto_otp() {
return auto_otp;
}
public void setAuto_otp(int auto_otp) {
this.auto_otp = auto_otp;
}
}
}
This is Vetify_otp
package com.motofacil.passageiro;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.motofacil.passageiro.accounts.RegistrationModel;
import com.motofacil.passageiro.accounts.ResultCheckMessage;
import com.motofacil.passageiro.accounts.ResultChecker;
import com.motofacil.passageiro.manager.ApiManager;
import com.motofacil.passageiro.manager.SessionManager;
import com.motofacil.passageiro.samwork.Config;
import com.motofacil.passageiro.urls.Apis;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hbb20.CountryCodePicker;
import java.util.HashMap;
public class Verify_OTP extends AppCompatActivity implements ApiManager.APIFETCHER {
ApiManager apiManager ;
GsonBuilder gsonBuilder;
RegistrationModel.OTP_Details otp_details;
private TextView otpError_txt;
private EditText otp_input, edt_enter_phone;
private LinearLayout submit_otp_layout;
SessionManager sessionManager ;
Gson gson;
String code, input_phone_number, otp;
CountryCodePicker codePicker;
private static final int KEY_REGISTER = 110;
Button generate_otp;
LinearLayout submit_otp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gsonBuilder = new GsonBuilder();
gson = gsonBuilder.create();
apiManager = new ApiManager(this , this , this );
sessionManager = new SessionManager(Verify_OTP.this);
otp_details = new RegistrationModel.OTP_Details();
setContentView(R.layout.activity_verify__otp);
gsonBuilder = new GsonBuilder();
gson = gsonBuilder.create();
submit_otp = (LinearLayout) findViewById(R.id.otp_submit);
generate_otp = (Button) findViewById(R.id.generate_otp);
edt_enter_phone = (EditText)findViewById(R.id.edt_enter_phone);
otp_input = (EditText)findViewById(R.id.otp_edt);
otpError_txt = (TextView)findViewById(R.id.otp_verifier_txt);
submit_otp_layout = (LinearLayout)findViewById(R.id.otp_submit);
codePicker = (CountryCodePicker)findViewById(R.id.otp_ccp);
submit_otp.setEnabled(false);
generate_otp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
input_phone_number = edt_enter_phone.getText().toString().trim();
Log.e("input_phone_number====", input_phone_number);
code = codePicker.getSelectedCountryCodeWithPlus();
Log.e("COUNTRY_CODE_PICKER===", code);
if (input_phone_number.equals("")){
Toast.makeText(Verify_OTP.this, R.string.required_field_missing, Toast.LENGTH_SHORT).show();
}else {
getOTP(code+input_phone_number);
}
}
});
submit_otp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (otp_input.getText().toString().equals("")) {
Toast.makeText(Verify_OTP.this, R.string.required_field_missing, Toast.LENGTH_SHORT).show();
} else if (!otp_input.getText().toString().equals(otp)) {
// Toast.makeText(Verify_OTP.this, R.string.invalid_otp, Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.putExtra("phone_number", code + input_phone_number);
setResult(Activity.RESULT_OK, intent);
finish();
} else {
Intent intent = new Intent();
intent.putExtra("phone_number", code + input_phone_number);
setResult(Activity.RESULT_OK, intent);
finish();
}
}
});
}
private void getOTP(String phone) {
HashMap<String , String > bodyparameters = new HashMap<String, String>();
bodyparameters.put("phone" , phone);
bodyparameters.put("flag" ,"1");
apiManager.execution_method_post(Config.ApiKeys.KEY_VERIFY_OTP ,""+ Apis.SEND_OTP, bodyparameters, true,ApiManager.ACTION_SHOW_TOP_BAR);
}
#Override
public void onFetchComplete(Object script, String APINAME) {
if(APINAME.equals(""+Config.ApiKeys.KEY_VERIFY_OTP)){
submit_otp.setEnabled(true);
RegistrationModel.OTP_Details otp_response = gson.fromJson("" + script, RegistrationModel.OTP_Details.class);
// finilalizeActivity();
Log.e("**OTP_SCRIPT-----", String.valueOf(otp_response.getMessage() + otp_response.getOtp() + otp_response.getStatus()));
otp = otp_response.getOtp();
Log.d("otp==normal sign up==", otp);
otp_input.setText(""+otp);
otp_input.requestFocus();
if(otp_response.getAuto_otp() == 1){
otp_input.setText(""+otp);
}
}else {
try{ResultChecker rcheck = gson.fromJson("" + script, ResultChecker.class);
Log.e("**OTP_SCRIPT-----", String.valueOf(script));
if(rcheck.getResult() == 1){
Log.e("**RCHHECKK---", String.valueOf(rcheck.getResult()));
RegistrationModel.OTP_Details otp_response = gson.fromJson("" + script, RegistrationModel.OTP_Details.class);
}else {
ResultCheckMessage rr = gson.fromJson("" + script, ResultCheckMessage.class);
Toast.makeText(this, ""+rr.getMessage(), Toast.LENGTH_SHORT).show();
}
}catch (Exception e){}
}
}
#Override
public void onFetchResultZero(String s) {
}
}
This is Activity_forgotpass_verify_otp.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.motofacil.passageiro.ForgotPass_Verify_OTP">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/pure_white"
android:orientation="horizontal">
<LinearLayout
android:id="#+id/otp_back"
android:layout_width="50dp"
android:layout_height="match_parent"
android:gravity="center"
android:visibility="invisible">
<ImageView
android:layout_width="20dp"
android:layout_height="20dp"
android:src="#drawable/ic_left_sort"
android:tint="#color/icons_8_muted_grey"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center">
<com.motofacil.passageiro.accounts.TypefaceDosisRegular
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/verifyOTP"
android:textColor="#color/icons_8_muted_grey"
android:textSize="16dp" />
</LinearLayout>
<LinearLayout
android:layout_width="50dp"
android:layout_height="match_parent" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/icons_8_muted_grey" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:src="#drawable/login_banner"></ImageView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#bf000000"></RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/icons_8_muted_grey" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center|top"
android:layout_marginTop="20dp"
android:gravity="center"
android:orientation="vertical">
<LinearLayout
android:id="#+id/phone_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:layout_marginLeft="15dp"
android:background="#drawable/shapes_white_transparent"
android:layout_marginRight="15dp"
android:gravity="center"
android:orientation="horizontal">
<com.hbb20.CountryCodePicker
android:id="#+id/otp_ccp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:hideNameCode="true"
app:keyboardAutoPopOnSearch="false"
app:showFlag="false"
android:layout_marginLeft="5dp"
app:defaultCode="55"
app:textSize="15dp"/>
<EditText
android:id="#+id/edt_enter_phone"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginLeft="10dp"
android:background="#android:color/transparent"
android:ems="10"
android:drawableTint="#color/icons_8_muted_grey"
android:gravity="center|left"
android:hint="Enter Phone Number"
android:inputType="phone"
android:maxLength="10"
android:minLines="1"
android:padding="5dp"
android:textColor="#color/pure_black"
android:textSize="17dp" />
</LinearLayout>
<!--
<View
android:layout_width="match_parent"
android:layout_height="0.85dp"
android:layout_marginBottom="10dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="6dp"
android:background="#color/icons_8_muted_yellow" />-->
<Button
android:id="#+id/generate_otp"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/generateOTP" />
<TextView
android:id="#+id/otp_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="35dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:text="#string/otp_text"
android:textColor="#color/pure_white"
android:textSize="17dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="70dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:gravity="center"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="30dp"
android:background="#drawable/shapes_white_transparent"
android:orientation="horizontal">
<EditText
android:id="#+id/otp_edt"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:background="#android:color/transparent"
android:drawableTint="#color/icons_8_muted_grey"
android:gravity="center|left"
android:hint="#string/enter_otp"
android:inputType="number"
android:paddingLeft="10dp"
android:textColor="#color/pure_black"
android:textSize="17dp" />
<TextView
android:id="#+id/otp_verifier_txt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:gravity="center|right"
android:padding="10dp"
android:text="Email not valid"
android:textColor="#color/icons_8_muted_red"
android:visibility="gone"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</ScrollView>
<LinearLayout
android:id="#+id/otp_submit"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#color/colorPrimary"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/submitOTP"
android:textColor="#color/pure_white"
android:textSize="16dp" />
</LinearLayout>
</LinearLayout>
</FrameLayout>
</LinearLayout>
Ready! I've submitted below the files I've listed. After typing the phone and clicking send otp, the code that comes back is always the code 2017, that is the first code I sent, but it only sends this code 2017 if the numbers start like this: 6599 .... if the number is so for example: 6598 .... it does not generate the code 2017 and can not continue the registration.

Toolbar doesn't set elevation on create or in XML

I'm currently creating an Android app for school but still want to give my best. I'm pretty new to Android development and coding in general.
The app is supposed to be a stock market game.
(Btw, I'm German, so there might be some German variables)
The app should have a similar style to Google's recent one with the Pixel 2 and Android Pie. Thus, the toolbar should have no drop shadow when created but it should appear when scrolling, like in the Pixel 2's settings app (e.g. the battery tab).
The drop shadow appears when scrolling and disappears when arriving at the top, but the toolbar starts with a drop shadow although I have set the android:elevation to 0 in the XML and also toolbar.setElevation(0) in the onCreate method.
Why does this happen? This method works in the OnScrollChangedListener!
The Java code:
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<JSONObject> jObjList = new ArrayList<>();
private FloatingActionButton fab;
private TextView moneyTxt;
private TextView sharesTxt;
private TextView sumTxt;
private Toolbar toolbar;
private AppBarLayout toolbarLayout;
private RecyclerView recyclerShares;
private SharesAdapter sAdapter;
private NestedScrollView scrollMain;
private SwipeRefreshLayout refreshMain;
private float money;
private float sharesWorth;
private boolean isRefreshing;
private JSONObject jObj = new JSONObject();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.abMain);
toolbar.setTitleTextColor(getResources().getColor(R.color.colorPrimary));
setSupportActionBar(toolbar);
fab = findViewById(R.id.fabMain);
moneyTxt = findViewById(R.id.moneyTxt);
sharesTxt = findViewById(R.id.sharesTxt);
sumTxt = findViewById(R.id.sumTxt);
toolbarLayout = findViewById(R.id.abMainLayout);
recyclerShares = findViewById(R.id.recyclerShares);
scrollMain = findViewById(R.id.scrollMain);
scrollMain.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
refreshMain = findViewById(R.id.refreshMain);
isRefreshing = false;
try {
jObj.put("name", "BMW");
jObj.put("worth", 143.23);
jObj.put("count", 5);
jObj.put("change", -1.5);
jObjList.add(jObj);
} catch (JSONException e) {
}
sAdapter = new SharesAdapter(jObjList);
RecyclerView.LayoutManager cLayoutManager = new CustomGridLayoutManager(getApplicationContext()) {
#Override
public boolean canScrollVertically() {
return false;
}
};
recyclerShares.setLayoutManager(cLayoutManager);
recyclerShares.setItemAnimator(new DefaultItemAnimator());
recyclerShares.setAdapter(sAdapter);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SharesActivity.class);
startActivity(intent);
}
});
toolbarLayout.setElevation(0); //TODO: Stackoverflow nach Lösung fragen
scrollMain.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
#Override
public void onScrollChanged() {
int scroll = scrollMain.getScrollY();
if (scroll == 0) {
toolbarLayout.setElevation(0);
} else {
toolbarLayout.setElevation(8);
}
}
});
refreshMain.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
refresh(MainActivity.this);
}
});
refresh(MainActivity.this);
}
private void refresh(Context context) {
isRefreshing = true;
SharedPreferences sharedPref = context.getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
SharedPreferences.Editor sharedPrefEdit = sharedPref.edit();
if (sharedPref.getBoolean("isFirstRun", true)) {
sharedPrefEdit.putBoolean("isFirstRun", false);
sharedPrefEdit.putFloat(getString(R.string.moneyShared), 5000);
sharedPrefEdit.apply();
}
float shareWorth = 0;
for (int i = 0; i < jObjList.size(); i++) {
try {
shareWorth += jObjList.get(i).getDouble("worth") * jObjList.get(i).getDouble("count");
} catch (JSONException e) {
}
}
sharedPrefEdit.putFloat(getString(R.string.sharesWorthShared), shareWorth);
sharedPrefEdit.commit();
money = sharedPref.getFloat(getString(R.string.moneyShared), 0);
sharesWorth = sharedPref.getFloat(getString(R.string.sharesWorthShared), 0);
moneyTxt.setText(String.format("%.2f€", money));
sharesTxt.setText(String.format("%.2f€", sharesWorth));
sumTxt.setText(String.format("%.2f€", money + sharesWorth));
if(isRefreshing) {
isRefreshing = false;
refreshMain.setRefreshing(isRefreshing);
}
Toast.makeText(MainActivity.this, "Alles neugeladen", Toast.LENGTH_SHORT).show();
}
public void onShareClick(View v) {
Intent i = new Intent(MainActivity.this, CompanyActivity.class);
try {
i.putExtra("name", jObj.getString("name"));
i.putExtra("worth", jObj.getDouble("worth"));
} catch (JSONException e) {
i.putExtra("name", "Fehler");
i.putExtra("worth", 0);
}
startActivity(i);
}
}
The XML code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorBackground"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/abMainLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="0dp">
<android.support.v7.widget.Toolbar
android:id="#+id/abMain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorBackgroundAccent"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fabMain"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="16dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:backgroundTint="#color/colorBackground"
android:src="#drawable/ic_note_add"
app:borderWidth="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/refreshMain"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/abMainLayout">
<android.support.v4.widget.NestedScrollView
android:id="#+id/scrollMain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusableInTouchMode="true"
app:layout_constraintTop_toBottomOf="#+id/abMainLayout">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<GridLayout
android:id="#+id/gridMoney"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorBackgroundAccent"
android:orientation="horizontal"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingTop="24dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/abMain">
<TextView
android:id="#+id/sumTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_columnSpan="5"
android:layout_columnWeight="1"
android:layout_gravity="center"
android:layout_marginBottom="16dp"
android:layout_marginTop="8dp"
android:layout_row="1"
android:textColor="#color/colorDarkText"
android:textSize="50sp"
android:textStyle="bold" />
<ImageView
android:id="#+id/moneyImg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="1"
android:layout_columnWeight="1"
android:layout_gravity="right|center_vertical"
android:layout_row="2"
android:background="#android:color/transparent"
android:scaleX="0.5"
android:scaleY="0.5"
app:srcCompat="#drawable/ic_money" />
<TextView
android:id="#+id/moneyTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="2"
android:layout_columnWeight="1"
android:layout_gravity="left|center_vertical"
android:layout_row="2"
android:background="#android:color/transparent"
android:textColor="#color/colorLightText"
android:textSize="15sp" />
<ImageView
android:id="#+id/sharesImg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="3"
android:layout_columnWeight="1"
android:layout_gravity="right|center_vertical"
android:layout_row="2"
android:background="#android:color/transparent"
android:scaleX="0.5"
android:scaleY="0.5"
app:srcCompat="#drawable/outline_assessment_black_36" />
<TextView
android:id="#+id/sharesTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_column="4"
android:layout_columnWeight="1"
android:layout_gravity="left|center_vertical"
android:layout_row="2"
android:background="#android:color/transparent"
android:textColor="#color/colorLightText"
android:textSize="15sp" />
</GridLayout>
<View
android:id="#+id/dividerMoney"
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/colorDivider"
app:layout_constraintTop_toBottomOf="#id/gridMoney" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="#dimen/recycler_horizontal_margin"
android:layout_marginStart="#dimen/recycler_horizontal_margin"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:text="Aktien"
android:textColor="#color/colorPrimary"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="#+id/dividerMoney"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/gridMoney" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerShares"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="#dimen/recycler_title_bottom_margin"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</android.support.v4.widget.SwipeRefreshLayout>
</android.support.constraint.ConstraintLayout>
So #NileshRathod answered it:
It's app:elevation, not android:elevation.
But I still don't get why the method in onCreate() doesn't work.
Of course, setElevation(0); won't work.
But I still don't get why the method in onCreate() doesn't work.
AppbarLayout uses StateListAnimator from v24.0.0 and that is why setElevation will has no effect on it: https://stackoverflow.com/a/37992366/4409113
So:
StateListAnimator stateListAnimator = new StateListAnimator();
stateListAnimator.addState(new int[0], ObjectAnimator.ofFloat(view, "elevation", 0));
appBarLayout.setStateListAnimator(stateListAnimator);
Or:
toolbarLayout = findViewById(R.id.abMainLayout);
toolbarLayout.StateListAnimator = null;
In your case.

How to add onClick for buttons?

I'm trying to figure out why my app crashes when my AddThreeToTeamA button crashes my application upon clicking. I have addded my XML and my Java code.
I am following a tutorial however it obviously does not crash and I have tried several different solutions.
Any hint will be appreciated.
package com.themovingmonkey.courtcounter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int score = 0;
int scoreTeamA;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void addThreeForTeamA() {
scoreTeamA = score + 3;
displayForTeamA(scoreTeamA);
}
public void addTwoForTeamA() {
scoreTeamA = score + 2;
displayForTeamA(scoreTeamA);
}
public void addOneForTeamA() {
scoreTeamA = score + 1;
displayForTeamA(scoreTeamA);
}
public void displayForTeamA(int score) {
TextView scoreView = (TextView) findViewById(R.id.Team_A_Score);
scoreView.setText(String.valueOf(scoreTeamA));
}
}
////////////////////////////////////////////////////////////////
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text= "Team A"
android:padding="4dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="0"
android:padding="4dp"
android:id="#+id/Team_A_Score"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="3 Points"
android:layout_margin="8dp"
android:onClick="addThreeForTeamA"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="2 Points"
android:layout_margin="8dp"
android:onClick="addTwoForTeamA"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="1 Point"
android:layout_margin="8dp"
android:onClick="addOneForTeamA"
/>
</LinearLayout>
All methods defined using the android:onClick="someMethod" attribute. Then they have to be public and should pass a View as the only parameter, Change your methods to:
public void someMethod(View view){
//Everything else!
}
Your methods do not pass a View as the only parameter at all currently!

Categories

Resources