I am doing a saving system with sharedPreferences, the problem is that when I run the application it seems that if the String is saved but when converting it to int later it returns null values or 0...
the edit text only receives numbers, and what I try is to obtain its value as a string and then convert it to int, since I want to use that value in another activity
package com.example.ml_prototipe_a;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class MainActivity extends AppCompatActivity {
private EditText inputLimiter;
private TextView mostrarLimite;
public String limiterStr;
public int limiterInt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mostrarLimite = (TextView)findViewById(R.id.MostrarAciertos);
inputLimiter = (EditText) findViewById(R.id.InLimAciertos);
limiterStr = inputLimiter.getText().toString().trim();
Button btnRecNotas = findViewById(R.id.recNotasBtn);
Button btnGuardarLim = findViewById(R.id.GuardarLimite);
btnRecNotas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intRecNotas = new Intent(MainActivity.this, MainRecNotas.class);
startActivityForResult(intRecNotas, 0);
}
});
btnGuardarLim.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
public void Cargar(View view){
SharedPreferences limitPrefs= getBaseContext().getSharedPreferences("limitData", Context.MODE_PRIVATE);
String recovaStr = limitPrefs.getString("numbreLimiter", "");
if(!"".equals(recovaStr)) {
limiterInt = Integer.parseInt(recovaStr);
mostrarLimite.setText("aciertos: " + limiterInt);
System.out.println(limiterInt);
}
}
public void Guardar(View view){
if(mostrarLimite!=null) {
SharedPreferences limitPrefs = getBaseContext().getSharedPreferences("limitData", Context.MODE_PRIVATE);
SharedPreferences.Editor editer = limitPrefs.edit();
editer.putString("numberLimiter", limiterStr);
editer.apply();
}
}
}
NEW CODE!!!!********************************
package com.example.ml_prototipe_a;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class MainActivity extends AppCompatActivity {
private EditText inputLimiter;
private TextView mostrarLimite;
public String limiterStr;
public int limiterInt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mostrarLimite = (TextView) findViewById(R.id.MostrarAciertos);
inputLimiter = (EditText) findViewById(R.id.InLimAciertos);
Button btnRecNotas = findViewById(R.id.recNotasBtn);
Button btnGuardarLim = findViewById(R.id.GuardarLimite);
Button btnCargarLimTEMP = findViewById(R.id.cargarTemp);
btnRecNotas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intRecNotas = new Intent(MainActivity.this, MainRecNotas.class);
startActivityForResult(intRecNotas, 0);
}
});
btnGuardarLim.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Guardar();
}
});
btnCargarLimTEMP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Cargar();
}
});
}
private void Cargar() {
SharedPreferences limitPrefs = getBaseContext().getSharedPreferences("limitData", Context.MODE_PRIVATE);
String recovaStr = limitPrefs.getString("numbreLimiter", "");
try {
limiterInt = Integer.parseInt(recovaStr);
} catch (NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
mostrarLimite.setText("aciertos: " + limiterInt);
System.out.println(limiterInt);
Toast.makeText(this, "Limite de aciertos: " + limiterInt, Toast.LENGTH_SHORT).show();
}
private void Guardar() {
if (mostrarLimite != null) {
SharedPreferences limitPrefs = getBaseContext().getSharedPreferences("limitData", Context.MODE_PRIVATE);
SharedPreferences.Editor editer = limitPrefs.edit();
editer.putString("numberLimiter", limiterStr);
editer.apply();
limiterStr = inputLimiter.getText().toString().trim();
Toast.makeText(this, "Limite de aciertos actualizado: " + limiterStr, Toast.LENGTH_SHORT).show();
System.out.println(limiterStr);
}
}
}
Related
The problem is that the progress bar only starts when the data has been processed. And I want it to run before processing the data, right after pressing the search button. What am I doing wrong?
whole fragment code
package com.app.comicslibrary.MenuFragments;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.app.comicslibrary.Jsoup.ParseBookInfo;
import com.app.comicslibrary.MainActivity;
import com.app.comicslibrary.MenuFragments.ListActions.AddPosition;
import com.app.comicslibrary.MenuFragments.ListActions.ModelCollectView;
import com.app.comicslibrary.MenuFragments.SearchMenu.SearchListAdapter;
import com.app.comicslibrary.R;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
public class SecondFragment extends Fragment {
ArrayList<ModelCollectView> listParseComics;
ArrayList<ModelCollectView> selectedComics;
SearchListAdapter searchArrayAdapter;
private ProgressBar loadingBar;
private Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_second, container, false);
EditText searchLine = (EditText) view.findViewById(R.id.searchLine);
Button searchButton = (Button) view.findViewById(R.id.searchButton);
ListView searchList = (ListView) view.findViewById(R.id.listViewSearch);
Button saveSearchButton = (Button) view.findViewById(R.id.buttonSaveSearch);
loadingBar = (ProgressBar)view.findViewById(R.id.loadingProgressBar);
listParseComics = new ArrayList<>();
//search and display result list
searchButton.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onClick(View v){
String textSearch = searchLine.getText().toString();
if(textSearch.isEmpty() || textSearch.length() <= 3){
Toast.makeText(getContext(), "Введите более 3 символов в строку поиска", Toast.LENGTH_SHORT).show();
return;
}
setLoadingProgressBarVisible();
ParseBookInfo getInfo = new ParseBookInfo(getContext());
try{
int SDK_INT = android.os.Build.VERSION.SDK_INT;
if (SDK_INT > 8)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
listParseComics = getInfo.searchComicsInfo(textSearch, 1);//change numberpage later
searchArrayAdapter = new SearchListAdapter(container.getContext(), listParseComics);
searchList.setAdapter(searchArrayAdapter);
}
}catch(IOException e){
Log.d("PARSEERROR", "Search comics is fail");
}
}
});
//select position and call add menu
selectedComics = new ArrayList<>();
saveSearchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listParseComics == null || searchArrayAdapter == null){
Toast.makeText(getContext(), "Нет данных для добавления", Toast.LENGTH_SHORT).show();
return;
}
boolean []statusItems = searchArrayAdapter.getChecked();
Intent intent = new Intent(getActivity(), AddPosition.class);
for (int i = 0; i < statusItems.length; i++) {
if(statusItems[i]){
ModelCollectView selectedItem = listParseComics.get(i);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
selectedItem.getImage().compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bytes = stream.toByteArray();
intent.putExtra("bytesImages" + i, bytes);
selectedItem.setImage(null);
selectedComics.add(selectedItem);
}
}
intent.putParcelableArrayListExtra("selectedItemsInSearch", selectedComics);
startActivity(intent);
}
});
return view;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
public void setLoadingProgressBarVisible(){
((MainActivity)context).runOnUiThread(new Runnable() {
public void run() {
Log.d("UI thread", "I am the UI thread");
loadingBar.setVisibility(View.VISIBLE);
}
});
}
}
The text of the log is displayed immediately, but the progress bar does not appear (function setLoadingProgressBarVisible())
I am beginner. I have made a simple log in form in android studio. I face a fault in if condition. Please solve this.
If username box is empty then control should go in if(...) but it goes to else part and open next intent
code is here:
package com.android.dumbseraaz;
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.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private EditText uname;
private EditText pwd;
private Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uname = (EditText)findViewById(R.id.txt_userName);
pwd = (EditText)findViewById(R.id.txt_Password);
login = (Button)findViewById(R.id.button);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(uname.getText().toString(),pwd.getText().toString());
}
});
}
private void validate(String myuname, String Pswd) {
if(myuname == "")
{
uname.setText("user");
}
else if(Pswd == "")
{
pwd.setText("PasswordMe");
}
else {
Intent intent = new Intent(MainActivity.this, app_home.class);
startActivity(intent);
}
}
}
I use Firebase Sms verification which sends OTP to the provided number. But the problem is it detects the number automatically if the number is within the phone.But i want to enter any number and when i put the number and i can access to the next activity by manually putting the otp. But in my case the the otp is received by any number(i mean outside of the device) but when i enter the code manually in the edittext, the app crashes.
Activity where the number is given and Otp send to the number
package com.example.bohon_final__001;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Random;
public class LoginActivity extends AppCompatActivity {
private EditText LoginPhone;
private Button LoginConfirmButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
LoginPhone = (EditText) findViewById(R.id.PhoneNumberLogin);
LoginConfirmButton = (Button) findViewById(R.id.Loginbutton);
Button registerbutton=(Button)findViewById(R.id.RegisterButton);
LoginConfirmButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String number=LoginPhone.getText().toString();
if(number.isEmpty() || number.length()<11)
{
LoginPhone.setError("Valied Number Required");
LoginPhone.requestFocus();
}
else {
String PhoneNumber = "+88" + number;
Intent firstintent = new Intent(LoginActivity.this, CodeConfirm.class);
firstintent.putExtra("PhoneNumber", PhoneNumber);
startActivity(firstintent);
}
}
});
registerbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(LoginActivity.this,User_Registration.class));
}
});
}
}
Activity that receives the OTP
package com.example.bohon_final__001;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.TaskExecutors;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
import java.util.concurrent.TimeUnit;
public class CodeConfirm extends AppCompatActivity {
EditText Otpverify;
int s;
private String VerificationCode;
Button confirmbutton,test;
private FirebaseAuth mAuth;
String code,PhoneNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_code_confirm);
Otpverify = (EditText) findViewById(R.id.ConfirmCode);
test=(Button)findViewById(R.id.testbutton);
mAuth= FirebaseAuth.getInstance();
PhoneNumber = getIntent().getStringExtra("PhoneNumber");
SendVerificationCode(PhoneNumber);
confirmbutton=(Button)findViewById(R.id.ConfirmButton);
test.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent nactivity=new Intent(CodeConfirm.this,Current_Location.class);
nactivity.putExtra("Phone",PhoneNumber);
startActivity(nactivity);
}
});
confirmbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
code=Otpverify.getText().toString().trim();
if(code.isEmpty() || code.length()<6)
{
Otpverify.setError("Enter the OTP properly");
Otpverify.requestFocus();
}
Verifycode(code);
}
});
}
private void Verifycode(String code) {
PhoneAuthCredential credential=PhoneAuthProvider.getCredential(VerificationCode,code);
Signin(credential);
}
private void Signin(PhoneAuthCredential credential) {
mAuth.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
Intent WorkingSwitch=new Intent(CodeConfirm.this,Current_Location.class);
WorkingSwitch.putExtra("Phone",PhoneNumber);
WorkingSwitch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(WorkingSwitch);
}
}
});
}
private void SendVerificationCode(String Number) {
PhoneAuthProvider.getInstance().verifyPhoneNumber(
Number,
60,
TimeUnit.SECONDS,
TaskExecutors.MAIN_THREAD,
mCallBack
);
}
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallBack = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
#Override
public void onVerificationCompleted(PhoneAuthCredential phoneAuthCredential) {
String code=phoneAuthCredential.getSmsCode();
if(code!=null)
{
Verifycode(code);
}
}
#Override
public void onVerificationFailed(FirebaseException e) {
Toast.makeText(CodeConfirm.this,e.getMessage(),Toast.LENGTH_LONG).show();
}
#Override
public void onCodeSent(String s, PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(s, forceResendingToken);
VerificationCode=s;
}
};
}
I've seen similar question but the answer is not satishfying.
I am developing attendance system and i have a listview with students name i want to programatically check or uncheck the radio buttons in the listview when the scanned qr matchs the student name I tried to do it in the ontextchengeListner method of txtresult but the text is changing many time even in reading a single qr
This are my java classes
CustomAdapter.java
package com.attendance.olana.qr_scanner;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by olana on 23/03/2018.
*/
public class CustomAdapter extends BaseAdapter {
Context context;
String[] questionsList;
public static String message;
LayoutInflater inflter;
public static TextView question ;
public static RadioButton yes,no ;
public static ArrayList<String> selectedAnswers;
public CustomAdapter(Context applicationContext, String[] questionsList) {
this.context = context;
this.questionsList = questionsList;
// initialize arraylist and add static string for all the questions
selectedAnswers = new ArrayList<>();
for (int i = 0; i < questionsList.length; i++) {
selectedAnswers.add("Not Attempted");
}
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return questionsList.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.main, null);
// get the reference of TextView and Button's
question = (TextView) view.findViewById(R.id.question);
yes = (RadioButton) view.findViewById(R.id.yes);
no = (RadioButton) view.findViewById(R.id.no);
// perform setOnCheckedChangeListener event on yes button
yes.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// set Yes values in ArrayList if RadioButton is checked
if (isChecked)
selectedAnswers.set(i, "Present");
}
});
// perform setOnCheckedChangeListener event on no button
no.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// set No values in ArrayList if RadioButton is checked
if (isChecked)
selectedAnswers.set(i, "Absent");
}
});
// set the value in TextView
question.setText(questionsList[i]);
return view;
}
}
list.java
package com.attendance.olana.qr_scanner;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.Toast;
/**
* Created by olana on 23/03/2018.
*/
public class list extends AppCompatActivity {
ListView simpleList;
public static String[] questions;
Button submit,scan;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
scan =(Button)findViewById(R.id.scan);
// get the string array from string.xml file
questions = getResources().getStringArray(R.array.student);
// get the reference of ListView and Button
simpleList = (ListView) findViewById(R.id.simpleListView);
submit = (Button) findViewById(R.id.submit);
// set the adapter to fill the data in the ListView
CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), questions);
simpleList.setAdapter(customAdapter);
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i;
i = new Intent(list.this,MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(i);
}
});
// perform setOnClickListerner event on Button
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String message = "";
// get the value of selected answers from custom adapter
for (int i = 0; i < CustomAdapter.selectedAnswers.size(); i++) {
message = message + "\n" + (i + 1) + " " + CustomAdapter.selectedAnswers.get(i);
}
// display the message on screen with the help of Toast.
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
});
}
}
MainActivity.java
package com.attendance.olana.qr_scanner;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Vibrator;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.SparseArray;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;
import java.io.IOException;
import java.util.jar.Manifest;
public class MainActivity extends AppCompatActivity {
BarcodeDetector barcodeDetector;
SurfaceView camerapreview;
CameraSource cameraSource;
TextView txtresult;
String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button finish = (Button) findViewById(R.id.finish);
//Button scan = (Button) findViewById(R.id.scan);
finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
});
camerapreview = (SurfaceView) findViewById(R.id.camerapreview);
txtresult = (TextView) findViewById(R.id.txtresult);
barcodeDetector = new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.QR_CODE)
.build();
cameraSource = new CameraSource
.Builder(this, barcodeDetector)
.setRequestedPreviewSize(640, 480)
.build();
//add event
camerapreview.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
cameraSource.start(camerapreview.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
try {
cameraSource.start(camerapreview.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrcodes = detections.getDetectedItems();
if (qrcodes.size() != 0) {
txtresult.post(new Runnable() {
#Override
public void run() {
//create vibration
Vibrator vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(100);
txtresult.setText(qrcodes.valueAt(0).displayValue);
//barcodeDetector.release();
}
});
}
}
});
}
}
Please tell me where i can implement these the programatically checking or unchecking the radio button when the name in the listview matchs the scanned qr please help me
I am having trouble trying to figure out how to save user inputted data into my app. I'm attempting to create a mock basketball statistics app that will store stats per each day and then average out the different stats. Before I can do any of the actual math, though, I cannot figure out how to save the data and load it.
This is the code that I have so far for both activities:
Main Activity
package com.miahollins.basketballfinal;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
int gamesp, gamest,points,perfoul;
Button btn;
int year_x,month_x,day_x;
static final int DIALOG_ID=0;
EditText games, game2, game3, game4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText game1 = (EditText) findViewById(R.id.games);
final EditText game2 = (EditText) findViewById(R.id.games2);
final EditText game3 = (EditText) findViewById(R.id.games3);
final EditText game4 = (EditText) findViewById(R.id.games4);
Button results = (Button) findViewById(R.id.button);
final SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
results.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
gamesp = Integer.parseInt(game1.getText().toString());
gamest = Integer.parseInt(game2.getText().toString());
points = Integer.parseInt(game3.getText().toString());
perfoul = Integer.parseInt(game4.getText().toString());
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("key1", gamesp);
editor.putInt("key2", gamest);
editor.putInt("key3", points);
editor.putInt("key4", perfoul);
editor.commit();
startActivity(new Intent(MainActivity.this, Status.class));
}
});
final Calendar cal = Calendar.getInstance();
year_x = cal.get(Calendar.YEAR);
month_x = cal.get(Calendar.MONTH);
day_x = cal.get(Calendar.DAY_OF_MONTH);
showDialogOnButtonClick();
}
public void save(View view){
String value = games.getText().toString();
String file_name="stats";
try {
FileOutputStream fileOutputStream = openFileOutput(file_name,MODE_PRIVATE);
fileOutputStream.write(value.getBytes());
fileOutputStream.close();
Toast.makeText(getApplicationContext(),"Message Saved",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void showDialogOnButtonClick(){
btn=(Button)findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(DIALOG_ID);
}
});
}
#Override
protected Dialog onCreateDialog(int id){
if (id==DIALOG_ID)
return new DatePickerDialog(this,dPickerListener,year_x,month_x,day_x);
return null;
}
private DatePickerDialog.OnDateSetListener dPickerListener= new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
year_x=year;
month_x=monthOfYear+1;
day_x=dayOfMonth;
Toast.makeText(MainActivity.this,year_x+" / " + month_x+" / "+day_x,Toast.LENGTH_LONG).show();
}
};
}
Second Activity
package com.miahollins.basketballfinal;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
public class Status extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.status);
}
public void load(View view){
try {
String Stats;
FileInputStream fileInputStream = openFileInput("stats");
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer stringBuffer = new StringBuffer();
while ((Stats=bufferedReader.readLine())!=null){
stringBuffer.append(Stats + "\n");
}
TextView load = (TextView)findViewById(R.id.textView);
load.setText(stringBuffer.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Any help would be greatly appreciated!