Storing user input data in Internal Memory - android

I'm tryin to create a simple app that basically is a tracker that keeps track of no. of classes for each subject for a college student. The app is specific to my college timetable. The idea is tht i have 3 activities: main.java, Sublist.java and editcrap.java. The main.java acts as a splash screen and starts the Sublist activity.
In the Sublist activity the user is displayed with a layout displaying (TextView) (Button) (Counter_TextView) horizontally with respect ot each other. There are 7 of these aligned vertically.
When the menu button is clicked: (Edit Subject Parameters) comes up which wen clicked takes the user to editcrap.java activity where the user input is taken in corresponding EditText boxes asking for subject name for each corresponding (TextView) and total number of classes corresponding to (Counter_TextView) in the Sublist activity. On the click of OK button the data is passed bak to Sublist activity for display and manipulation.
Having done this I needed a way to store the data so tht the next time the app is opened it wud retain its previous string and no. of classes values. This is where I'm running into force close errors or No retention of data error. Here is my code...cud someone please tell me wat m doin wrong? I've been struggling for days with this :) I basically need the app to maintain 2 files one containing Strings and the other Numbers that need to be read from and displayed in Sublist.java activity as we i need any changes done by the app user to be reflected unto the original files as well
//Sublist.java:
package com.shuaib669.bunkrecord;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class Sublist extends Activity{
double[] no_of_classes = new double[7];
int count[]= new int[7];
double cutOff = 0.3;
String[] newText = new String[7];
String[] newNum = new String[7];
String countString = null;
TextView subject[] = new TextView[7];
TextView counter[] = new TextView[7]; //sub11 is counter text view label
Button button[] = new Button[7]; //button1 is the increment button
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Assigning Views to objects.
subject[0] = (TextView) findViewById(R.id.textView1);
counter[0] = (TextView) findViewById(R.id.counter1);
button[0] = (Button) findViewById(R.id.button1);
subject[1] = (TextView) findViewById(R.id.textView2);
counter[1] = (TextView) findViewById(R.id.counter2);
button[1] = (Button) findViewById(R.id.button2);
subject[2] = (TextView) findViewById(R.id.textView3);
counter[2] = (TextView) findViewById(R.id.counter3);
button[2] = (Button) findViewById(R.id.button3);
subject[3] = (TextView) findViewById(R.id.textView4);
counter[3] = (TextView) findViewById(R.id.counter4);
button[3] = (Button) findViewById(R.id.button4);
subject[4] = (TextView) findViewById(R.id.textView5);
counter[4] = (TextView) findViewById(R.id.counter5);
button[4] = (Button) findViewById(R.id.button5);
subject[5] = (TextView) findViewById(R.id.textView6);
counter[5] = (TextView) findViewById(R.id.counter6);
button[5] = (Button) findViewById(R.id.button6);
subject[6] = (TextView) findViewById(R.id.textView7);
counter[6] = (TextView) findViewById(R.id.counter7);
button[6] = (Button) findViewById(R.id.button7);
try {
// open the file for reading
DataInputStream in= new DataInputStream(openFileInput(getFilesDir() + "/" + "subject.txt"));
// if file the available for reading
if (in!= null) {
// prepare the file for reading
String line;
int x=0;
// read every line of the file into the line-variable, on line at the time
while(in.readLine() != null) {
// do something with the strings from the file
line=DataInputStream.readUTF(in);
subject[x].setTextColor(Color.BLACK);
subject[x].setText(line);
x+=1;
}
}
// close the file again
in.close();
}
catch (Exception e) {
e.printStackTrace();// do something if the myfilename.txt does not exits
}
button[0].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(count[0]>=(no_of_classes[0]*cutOff)){
counter[0].setTextColor(Color.RED);
countString = "" +(++count[0]); //Convert from int to String to set in your textview::
counter[0].setText(countString);
}
else{
countString = "" +(++count[0]); //Convert from int to String to set in your textview::
counter[0].setText(countString);
}
}
});
button[1].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(count[1]>=(no_of_classes[1]*cutOff)){
counter[1].setTextColor(Color.RED);
countString = "" +(++count[1]); //Convert from int to String to set in your textview::
counter[1].setText(countString);
}
else{
countString = "" +(++count[1]); //Convert from int to String to set in your textview::
counter[1].setText(countString);
}
}
});
button[2].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(count[2]>=(no_of_classes[2]*cutOff)){
counter[2].setTextColor(Color.RED);
countString = "" +(++count[2]); //Convert from int to String to set in your textview::
counter[2].setText(countString);
}
else{
countString = "" +(++count[2]); //Convert from int to String to set in your textview::
counter[2].setText(countString);
}
}
});
button[3].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(count[3]>=(no_of_classes[3]*cutOff)){
counter[3].setTextColor(Color.RED);
countString = "" +(++count[3]); //Convert from int to String to set in your textview::
counter[3].setText(countString);
}
else{
countString = "" +(++count[3]); //Convert from int to String to set in your textview::
counter[3].setText(countString);
}
}
});
button[4].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(count[4]>=(no_of_classes[4]*cutOff)){
counter[4].setTextColor(Color.RED);
countString = "" +(++count[4]); //Convert from int to String to set in your textview::
counter[4].setText(countString);
}
else{
countString = "" +(++count[4]); //Convert from int to String to set in your textview::
counter[4].setText(countString);
}
}
});
button[5].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(count[5]>=(no_of_classes[5]*cutOff)){
counter[5].setTextColor(Color.RED);
countString = "" +(++count[5]); //Convert from int to String to set in your textview::
counter[5].setText(countString);
}
else{
countString = "" +(++count[5]); //Convert from int to String to set in your textview::
counter[5].setText(countString);
}
}
});
button[6].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(count[6]>=(no_of_classes[6]*cutOff)){
counter[6].setTextColor(Color.RED);
countString = "" +(++count[6]); //Convert from int to String to set in your textview::
counter[6].setText(countString);
}
else{
countString = "" +(++count[6]); //Convert from int to String to set in your textview::
counter[6].setText(countString);
}
}
});
}
public boolean onCreateOptionsMenu(Menu menu){ // What the MENU button does.
super.onCreateOptionsMenu(menu);
MenuInflater castle = getMenuInflater();
castle.inflate(R.menu.main_menu, menu);
return(true);
}
public boolean onOptionsItemSelected(MenuItem item){ // Opens Options of MENU.
switch(item.getItemId()){
case R.id.editcrap: startActivityForResult((new Intent("com.shuaib669.bunkrecord.EDITCRAP")), 1);
return(true);
}
return(false);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case 1: if(resultCode==Activity.RESULT_OK){
newText = data.getStringArrayExtra("com.shuaib669.bunkrecord.thetext");
newNum = data.getStringArrayExtra("com.shuaib669.bunkrecord.thenum");
try {
// open myfilename.txt for writing
DataOutputStream out = new DataOutputStream(openFileOutput(getFilesDir() + "/" + "subject.txt", Context.MODE_PRIVATE));
//newNum = data.getIntArrayExtra("com.shuaib669.thenum");
//for loop to setText in the TextViews of main.xml
for(int x=0;x<7;x++){
subject[x].setTextColor(Color.BLACK);
subject[x].setText(newText[x]);
// write the contents on mySettings to the file
out.writeUTF(newText[x]);
try{
no_of_classes[x]=Integer.parseInt(newNum[x]);
}
catch(Exception nfe){
nfe.printStackTrace();
}
// close the file
out.close();
}
}
catch (Exception e) {
Log.i("Data Input Sample", "I/O Error"); //do something if an Exception occurs.
}
}
break;
}
}
}
//editcrap.java:
package com.shuaib669.bunkrecord;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class editcrap extends Activity{
EditText sub[] = new EditText[7]; //list of subject text edit labels.
Button parambutton1; //OK buttons for edit list.
EditText num[] = new EditText[7]; //list of objects of total no. of classes bunked edit text labels. (boinkers i know)
String theText[] = new String[7];
String theNum[] = new String[7];
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.params);
sub[0] = (EditText) findViewById(R.id.peditText1); //pedittext is the parameter menu edit text label
num[0] = (EditText) findViewById(R.id.pnumText1); //EditText label for takin in total no. of classes for 1 subject
sub[1] = (EditText) findViewById(R.id.peditText2);
num[1] = (EditText) findViewById(R.id.pnumText2);
sub[2] = (EditText) findViewById(R.id.peditText3);
num[2] = (EditText) findViewById(R.id.pnumText3);
sub[3] = (EditText) findViewById(R.id.peditText4);
num[3] = (EditText) findViewById(R.id.pnumText4);
sub[4] = (EditText) findViewById(R.id.peditText5);
num[4] = (EditText) findViewById(R.id.pnumText5);
sub[5] = (EditText) findViewById(R.id.peditText6);
num[5] = (EditText) findViewById(R.id.pnumText6);
sub[6] = (EditText) findViewById(R.id.peditText7);
num[6] = (EditText) findViewById(R.id.pnumText7);
parambutton1 = (Button) findViewById(R.id.parambutton1); //pbutton1 is the ok button to accept the input.
parambutton1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
for(int x=0;x<7;x++){
theText[x] = sub[x].getText().toString();
theNum[x] = num[x].getText().toString();
//theNum[x] = Integer.parseInt(num[x].getText().toString());
}
Intent data = new Intent(editcrap.this, Sublist.class);
data.putExtra("com.shuaib669.bunkrecord.thetext", theText);
data.putExtra("com.shuaib669.bunkrecord.thenum", theNum);
setResult(Activity.RESULT_OK, data);
finish();
}
});
}
}

Using Shared Preferences
public static final String PREFS_NAME = "MyPrefsFile";
private static final String PREF_USERNAME = "username";
private static final String PREF_PASSWORD = "password";
following code in onCreate() method
EtUserName=(EditText) findViewById(R.id.EditText01);
EtPassword=(EditText) findViewById(R.id.EditText02);
here you get Preferences value in editText...(if you have previous save Preferences)
SharedPreferences pref = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
String username = pref.getString(PREF_USERNAME, null);
String password = pref.getString(PREF_PASSWORD, null);
EtUserName.setText(username);
EtPassword.setText(password);
following code in check box click event...(save Preferences here)
String us,pa;
us=EtUserName.getText().toString();
pa=EtPassword.getText().toString();
SharedPreferences settings = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
getSharedPreferences(PREFS_NAME,MODE_PRIVATE)
.edit()
.putString(PREF_USERNAME, us)
.putString(PREF_PASSWORD, pa)
.commit();
for more information click here.and here

Related

How can I control the Recycle View by clicking on the date of the calendar view?

I'm new in android and also new in English sorry my bad English...
I have learned android course at the academy.
My sentence may be wrong because it is written through a translator. I hope you understand with a generous heart.
Here's what I want:
If I click 15 days in Calendar View,
It is hoped that only the 15th day information will be shown in the Recyclerview. If I click on another date in calenderview, for example, 20 days, I hope that the 15th item will disappear and only the 20th item view will be displayed.
Here's what I'm trying to do.
When I click a date in a calendar view, I want to see the Item View corresponding to that date.
package com.example.myapplication;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.icu.util.Calendar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class Calender extends AppCompatActivity {
// CalendarView myCalenderView;
// TextView schedule1, schedule11;
String a, b, c;
static String data1;
long Now;
Date date;
java.text.SimpleDateFormat mFormat = new SimpleDateFormat("YYYY_MM_dd");
TextView datetext;
Context mcontext;
private String getTime() {
Now = System.currentTimeMillis();
date = new Date(Now);
return mFormat.format(date);
}
private ArrayList<calenderArrayList> mArrayList = new ArrayList<>();
private ArrayList<calenderArrayList> bArrayList = new ArrayList<>();
SharedPreferences preferences;
SharedPreferences.Editor editor;
private static String TAG = "recyclerview_example";
//private ArrayList<calenderArrayList> mArrayList;
//ArrayList 선언
calendarAdapter mAdapter = new calendarAdapter(this, mArrayList);
//mAdapter 선언
// calendarAdapter bAdapter = new calendarAdapter(this, bArrayList);
private RecyclerView mRecyclerView;
private LinearLayoutManager mLinearLayoutManager;
private int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calender);
Log.d("스케쥴선택액티비티", "OnCreate()실행");
SharedPreferences calender_load = getSharedPreferences("calender", MODE_PRIVATE);
calender_load.getInt("save_size", 0);
int calender_size = calender_load.getInt("save_size", 0);
Log.d("시작시b사이즈1", "" + calender_size);
Log.d("시작시b사이즈1", "" + bArrayList.size());
Log.d("시작시m사이즈1", "" + mArrayList.size());
if (calender_size != 0) {
for (int i = 0; i < calender_size; i++) {
calenderArrayList calender = new calenderArrayList(calender_load.getString("save_date" + i, ""), calender_load.getString("save_work" + i, ""), calender_load.getString("save_place" + i, ""), calender_load.getBoolean("save_box" + i, false));
if (calender.number_exam.equals(data1)) {
Log.d("불러오기값", "" + calender_load.getString("save_date" + i, ""));
bArrayList.add(calender);
mArrayList.add(calender);
}
mAdapter = new calendarAdapter(this, mArrayList);
mAdapter.notifyDataSetChanged();
}
} else if (calender_size == 0) {
mAdapter = new calendarAdapter(this, mArrayList);
mAdapter.notifyDataSetChanged();
}
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view_exam);
//recycler_view라는 id를 가진 recycler_view를 mRecyclerView로 지정해준다.
mRecyclerView.addItemDecoration(new DividerItemDecoration(mRecyclerView.getContext(), 1));
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
//RecyclerView 내에 Item view들의 크기를 측정하고 위치를 지정
//언제 item view를 재사용해야하는지에 대한 정책을 결정하고 결정.
//mArrayList = new ArrayList<>();
mAdapter = new calendarAdapter(this, mArrayList);
//RecyclerView 내에 보여지는 view 들에 date set을 binding 시켜주는 역할.
//binding? 데이터 끼리 묵어준다?
mRecyclerView.setAdapter(mAdapter);
//mRecyclerView의 Adapter를 mAdapter로 set한다.
//set? 지정한다. 놓다. 위치하다.
// myCalenderView = (CalendarView) findViewById(R.id.calendar);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
// Toast.makeText(getApplicationContext(), "onStart()", Toast.LENGTH_SHORT).show();
Log.d("스케쥴선택액티비티", "OnStart()실행");
Log.d("스케쥴선택액티비티", "OnResume()실행");
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// Toast.makeText(getApplicationContext(), "onResume()", Toast.LENGTH_SHORT).show();
final CalendarView calendar = (CalendarView) findViewById(R.id.calendar);
calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
data1 = year + "/" + (month + 1) + "/" + dayOfMonth;
String a = data1 + dayOfMonth;
Log.d("날짜", "" + a);
ArrayList<calenderArrayList> dayofMonth = new ArrayList<>();
Log.d("어떤 이름으로?", "" + dayofMonth);
if (dayofMonth.size() != 0) {
SharedPreferences load = getSharedPreferences("" + data1, MODE_PRIVATE);
}
/* if(mArrayList.size()!=0) {
for (int i=0; i<mArrayList.size() ; i++) {
SharedPreferences save11 = getSharedPreferences("save", MODE_PRIVATE );
SharedPreferences.Editor save_editor = save11.edit();
save_editor.putBoolean("save_box"+i+mArrayList.get(i).number_exam, mArrayList.get(i).selected );
save_editor.putString("save_date"+i+mArrayList.get(i).number_exam, mArrayList.get(i).number_exam);
save_editor.putString("save_work"+i+mArrayList.get(i).number_exam, mArrayList.get(i).content_exam);
save_editor.putString("save_place"+i+mArrayList.get(i).number_exam, mArrayList.get(i).content_exam2);
save_editor.putInt("save_size"+mArrayList.get(i).number_exam, mArrayList.size());
save_editor.commit();
}
}
mArrayList.clear();
if(mArrayList.size()!=0)
{
for (int i =0; i<mArrayList.size(); i++){
if(mArrayList.get(i).number_exam.equals(data1)){
}
}
}*/
//int a = dayOfMonth;
Toast.makeText(Calender.this, year + "/" + (month + 1) + "/" + dayOfMonth, Toast.LENGTH_SHORT).show();
Log.d("리사이클러뷰 실행 전", "실행 전");
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view_exam);
Log.d("리사이클러뷰 실행 후", "실행 후");
final EditText number_exam = (EditText) view.findViewById(R.id.calender_date);
final EditText content_exam = (EditText) view.findViewById(R.id.calender_place);
final EditText content_exam2 = (EditText) view.findViewById(R.id.calender_content);
//TextView ee = findViewById(R.id.number_exam);
Log.d("사이즈 측정 실행 전", "실행 전");
ArrayList<calenderArrayList> calenderArrayLists = new ArrayList<>();
Log.d("실행11111", mAdapter.getItemCount() + "");
Log.d("뭐가 들어있나?", "" + mArrayList);
Log.d("뭐가 들어있나?", "" + mArrayList.size());
// Log.d("뭐가 들어았나?", ""+mArrayList.get(1).number_exam.toString());
// Log.d("뭐가 들어았나?", ""+mArrayList.get(2).number_exam.toString());
// Log.d("뭐가 들어았나?", ""+mArrayList.get(3).number_exam.toString());
if (mArrayList.size() != 0) {
Log.d("if구문 실행됨?", "" + mArrayList.size());
//1. 일단 뷰 자체를 초기화 해주어야함.
//2. 초기화 된 뷰에 다시 mArrayList에서 선정 된 정보를 다시 나타내주어야한다.
/* for(int i = 0; i<mArrayList.size(); i++){
Log.d("얼마?", ""+i);
Log.d("for 구문 작동?실행", "여기까진 접속?");
if(mArrayList.get(i).number_exam.toString().contains(a)){
Log.d("뭐가 들어있나? 실행여부", ""+mArrayList.get(i).number_exam.toString());
a = mArrayList.get(i).number_exam;
b = mArrayList.get(i).content_exam;
c = mArrayList.get(i).content_exam2;
//mArrayList.add(mArrayList.get(i));
}
}*/
}
}
});
Button buttonInsert_exam = (Button) findViewById(R.id.exam_button);
//button 클릭시 발생하는 이벤트를 나타낸다. 여기서는 입력하기 버튼 클릭시 발생하는 상황.
buttonInsert_exam.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(Calender.this);
View view = LayoutInflater.from(Calender.this)
.inflate(R.layout.activity_calender_edit_box, null, false);
builder.setView(view);
final Button ButtonSubmit_exam = (Button) view.findViewById(R.id.button_dialog_submit_exam);
final EditText number_exam = (EditText) view.findViewById(R.id.calender_date);
final EditText content_exam = (EditText) view.findViewById(R.id.calender_place);
final EditText content_exam2 = (EditText) view.findViewById(R.id.calender_content);
// final EditText editTextKorean = (EditText) view.findViewById(R.id.edittext_dialog_korean);
ButtonSubmit_exam.setText("입력하기");
number_exam.setText(data1);
final AlertDialog dialog = builder.create();
dialog.show();
//dialog에 나타나는 입력하기 버튼을 눌렀을 때 발생하는 상황
ButtonSubmit_exam.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String strID = number_exam.getText().toString();
String strID2 = content_exam.getText().toString();
String strID3 = content_exam2.getText().toString();
//number와 content view에 입력한 문자열을 strID, strID2에 담는다.
//String strKorean = editTextKorean.getText().toString();
calenderArrayList dict = new calenderArrayList(strID, strID2, strID3);
bArrayList.add(0, dict);
mArrayList.add(0, dict); //첫 줄에 삽입
//mArrayList.add(dict); //마지막 줄에 삽입
mAdapter.notifyDataSetChanged(); //변경된 데이터를 화면에 반영
Log.d("b사이즈", "" + bArrayList.size());
Log.d("m사이즈", "" + mArrayList.size());
dialog.dismiss();
//dialog를 종료 시켜준다.
}
});
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
// Toast.makeText(getApplicationContext(), "onPause()", Toast.LENGTH_SHORT).show();
SharedPreferences calendersave = getSharedPreferences("calender", MODE_PRIVATE);
SharedPreferences.Editor calendersaveeditor = calendersave.edit();
//calenderArrayList calenderArrayList = new calenderArrayList();
if (bArrayList.size() != 0) {
for (int i = 0; i < bArrayList.size(); i++) {
calendersaveeditor.putBoolean("save_box" + i, bArrayList.get(i).selected);
calendersaveeditor.putString("save_date" + i, bArrayList.get(i).number_exam);
calendersaveeditor.putString("save_work" + i, bArrayList.get(i).content_exam);
calendersaveeditor.putString("save_place" + i, bArrayList.get(i).content_exam2);
calendersaveeditor.putInt("save_size", bArrayList.size());
calendersaveeditor.commit();
Log.d("종료시b사이즈", "" + bArrayList.size());
Log.d("종료시m사이즈", "" + mArrayList.size());
}
} else if (bArrayList.size() == 0) {
calendersaveeditor.clear();
calendersaveeditor.commit();
}
Log.d("스케쥴선택액티비티", "OnPause()실행");
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
// Toast.makeText(getApplicationContext(), "onStop()", Toast.LENGTH_SHORT).show();
/*
* if(mArrayList.size()!=0){
for(int i = 0; i< mArrayList.size(); i++){
calendersaveeditor.putBoolean("save_box"+i, mArrayList.get(i).selected);
calendersaveeditor.putString("save_date"+i, mArrayList.get(i).number_exam);
calendersaveeditor.putString("save_work"+i, mArrayList.get(i).content_exam);
calendersaveeditor.putString("save_place"+i, mArrayList.get(i).content_exam2);
calendersaveeditor.putInt("save_size", mArrayList.size());
calendersaveeditor.commit();
}
}
else if(mArrayList.size()==0){
calendersaveeditor.clear();
calendersaveeditor.commit();
}
*/
Log.d("스케쥴선택액티비티", "OnStop()실행");
}
#Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
// Toast.makeText(getApplicationContext(), "onRestart()", Toast.LENGTH_SHORT).show();
Log.d("스케쥴선택액티비티", "OnRestart()실행");
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// Toast.makeText(getApplicationContext(), "onDestroy()", Toast.LENGTH_SHORT).show();
Log.d("스케쥴선택액티비티", "OnDestroy()실행");
}
}
First you need to add new entry in your existing mArrayList as i am can see from your code you are adding all existing entries again but not new entry.
After that you need to set adapter again with new mArrayList only then you will be able to see new data in your recycler view.

How can i send messages in the background without having to run the application everytime

I want to send messages to users whenever the temperature is higher than the threshold value.
This is the screen which sends the messages.The application should be running in the background and keep checking if the temperature goes beyond the threshold value and den should send the message.
package com.gopal.coldstorage;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.gopal.coldstorage.R;
import java.util.Calendar;
public class Dashboard extends Activity {
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
String sn, de, da, ti, te;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
TextView tv1 = (TextView) findViewById(R.id.textView22);
TextView hi = (TextView) findViewById(R.id.textView13);
TextView lo = (TextView) findViewById(R.id.textView14);
TextView hi1 = (TextView) findViewById(R.id.textView15);
TextView lo1 = (TextView) findViewById(R.id.textView19);
TextView hig = (TextView) findViewById(R.id.textView16);
TextView lowe = (TextView) findViewById(R.id.textView17);
TextView higherm = (TextView) findViewById(R.id.textView18);
TextView lowerm = (TextView) findViewById(R.id.textView20);
int count = 0, count1 = 0, count1m = 0, countm = 0, tm = 0;
SQLiteDatabase db = openOrCreateDatabase("SData", MODE_PRIVATE, null);
Cursor cur = db.rawQuery("select distinct temp from sdata where date='2016-03-03'", null);
cur.moveToLast();
int c1 = cur.getColumnIndex("temp");
String temp = cur.getString(c1);
final int t = Integer.parseInt(temp);
tv1.setText(temp);
Calendar c = Calendar.getInstance();
Cursor cur1 = db.rawQuery("select max(temp) as max,min(temp) as min from sdata where date='2016-03-03'", null);
cur1.moveToFirst();
int id = cur1.getColumnIndex("max");
int id1 = cur1.getColumnIndex("min");
String max = cur1.getString(id);
String min = cur1.getString(id1);
hi.setText(max);
lo.setText(min);
SQLiteDatabase dbn = openOrCreateDatabase("thres", MODE_PRIVATE, null);
Cursor curser1 = db.rawQuery("select temp from sdata where date='2016-03-03'", null);
curser1.moveToFirst();
int high = 0;
int low = 0;
if (curser1 != null) {
do {
int c11 = curser1.getColumnIndex("temp");
String tempd = curser1.getString(c11);
int td = Integer.parseInt(tempd);
Cursor curs = dbn.rawQuery("select high,low from threshold", null);
curs.moveToLast();
int c2 = curs.getColumnIndex("high");
int c3 = curs.getColumnIndex("low");
String h1 = curs.getString(c2);
String l1 = curs.getString(c3);
high = Integer.parseInt(h1);
if (td > high) {
count++;
}
low = Integer.parseInt(l1);
if (td < low) {
count1++;
}
} while (curser1.moveToNext());
}
hig.setText(String.valueOf(count));
lowe.setText(String.valueOf(count1));
Cursor curn = db.rawQuery("select temp from sdata where date like '2016-03%'", null);
curn.moveToFirst();
if (curn != null) {
do {
int cn = curn.getColumnIndex("temp");
String tempm = curn.getString(cn);
tm = Integer.parseInt(tempm);
Cursor curser = dbn.rawQuery("select high,low from threshold", null);
curser.moveToLast();
int c2 = curser.getColumnIndex("high");
int c3 = curser.getColumnIndex("low");
String h1 = curser.getString(c2);
String l1 = curser.getString(c3);
int highm = Integer.parseInt(h1);
if (tm > highm) {
countm++;
}
int lowm = Integer.parseInt(l1);
if (tm < lowm) {
count1m++;
}
} while (curn.moveToNext());
}
higherm.setText(String.valueOf(countm));
lowerm.setText(String.valueOf(count1m));
Cursor cur2 = db.rawQuery("select max(temp) as max,min(temp) as min from sdata where date like '2016-03%'", null);
cur2.moveToFirst();
int id2 = cur2.getColumnIndex("max");
int id3 = cur2.getColumnIndex("min");
String max1 = cur2.getString(id2);
String min1 = cur2.getString(id3);
hi1.setText(max1);
lo1.setText(min1);
final TextView tv = (TextView) findViewById(R.id.textView23);
Bundle b = getIntent().getExtras();
String s = b.getString("value");
tv.setText(s);
TextView time = (TextView) findViewById(R.id.textView21);
String sTime = c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND);
time.setText(sTime);
TextView date = (TextView) findViewById(R.id.textView3);
String mon = null;
int month = c.get(Calendar.MONTH) + 1;
switch (month) {
case 1:
mon = "JAN";
break;
case 2:
mon = "FEB";
break;
case 3:
mon = "MAR";
break;
case 4:
mon = "APR";
break;
case 5:
mon = "MAY";
break;
case 6:
mon = "JUN";
break;
case 7:
mon = "JUL";
break;
case 8:
mon = "AUG";
break;
case 9:
mon = "SEPT";
break;
case 10:
mon = "OCT";
break;
case 11:
mon = "NOV";
break;
case 12:
mon = "DEC";
break;
}
String sDate = c.get(Calendar.DATE) + "-" + mon + "-" + c.get(Calendar.YEAR);
date.setText(sDate);
TextView months = (TextView) findViewById(R.id.textView8);
months.setText(mon);
if (t > high) {
SQLiteDatabase dbn1 = openOrCreateDatabase("sample", MODE_PRIVATE, null);
Cursor c111 = dbn1.rawQuery("select phno from user", null);
c111.moveToFirst();
if (c111 != null) {
do {
int c12 = c111.getColumnIndex("phno");
final String phn = c111.getString(c12);
final int finalHigh = high;
AlertDialog.Builder a = new AlertDialog.Builder(this);
a.setTitle("Alert");
a.setMessage("The current temperature is " + t + " which is greater than the threshold value " + finalHigh);
a.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
a.show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phn, null, "The current temperature is " + t + " which is greater than the threshold value " + finalHigh,
null, null);
}
}, 50000);
Toast.makeText(getApplicationContext(),
"Messages sent", Toast.LENGTH_SHORT).show();
} while (c111.moveToNext());
}
}
if (t < low) {
SQLiteDatabase dbn1 = openOrCreateDatabase("sample", MODE_PRIVATE, null);
Cursor c111 = dbn1.rawQuery("select phno from user", null);
c111.moveToFirst();
if (c111 != null) {
do {
int c12 = c111.getColumnIndex("phno");
final String phn = c111.getString(c12);
final int finalHigh = high;
final int finalLow = low;
AlertDialog.Builder a = new AlertDialog.Builder(this);
a.setTitle("Alert");
a.setMessage("The current temperature is \" + t + \" which is lesser than the threshold value " + finalLow);
a.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
a.show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phn, null, "The current temperature is " + t + " which is lesser than the threshold value " + finalLow,
null, null);
}
}, 50000);
Toast.makeText(getApplicationContext(),
"Messages sent", Toast.LENGTH_SHORT).show();
} while (c111.moveToNext());
}
}
Button b1 = (Button) findViewById(R.id.button2);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(Dashboard.this);
alert.setTitle("Choose");
final String[] a = {"Temperature Log", "High Temperature", "Low Temperature"};
alert.setItems(a, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
if (a[arg1].equals("Temperature Log")) {
Intent in = new Intent(
Dashboard.this, Templog.class);
//
// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
startActivity(in);
Dashboard.this.finish();
}
if (a[arg1].equals("High Temperature")) {
Intent i = new Intent(Dashboard.this, Highlog.class);
// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
startActivity(i);
Dashboard.this.finish();
// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
if (a[arg1].equals("Low Temperature")) {
Intent intent = new Intent(Dashboard.this, Lowlog.class);
startActivity(intent);
Dashboard.this.finish();
}
}
});
alert.show();
}
});
}
}
A service is a component which runs in the background, without direct interaction with the user. As the service has no user interface it is not bound to the lifecycle of an activity. Services are used for repetitive and potential long running operations, checking for new data, data processing, indexing content, etc.
try to following Link :
[click][1]
[1]: https://github.com/codepath/android_guides/wiki/Starting-Background-Services
Use Service to send message in background.
A Service is an application component that can perform long-running operations in the background and does not provide a user interface. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC).
Follow the below Link it will help you
http://developer.android.com/guide/components/services.html

how to set the button so as not to force close when empty EditText [duplicate]

getting an error of invalid Double
java.lang.numberformatexception invalid double: ""
what is the reason for this
Activity 1
package com.example.solarcalculator;
import android.os.Bundle;
import android.widget.Button;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.app.AlertDialog;
import android.content.Intent;
#SuppressLint("UseValueOf")
public class MainActivity extends Activity {
private EditText input1;
private EditText input2;
private EditText input3;
private EditText input4;
private EditText input5;
private MainActivity mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.activity_main);
input5 = (EditText) findViewById(R.id.input5);
Button button1 = (Button) findViewById(R.id.button1);
input4 = (EditText) findViewById(R.id.input4);
input1 = (EditText) findViewById(R.id.input1);
input2 = (EditText) findViewById(R.id.input2);
input3 = (EditText) findViewById(R.id.input3);
button1.setOnClickListener(new OnClickListener() {
#SuppressWarnings("unused")
private AlertDialog show;
#SuppressLint("UseValueOf")
#Override
public void onClick(View arg0) {
if ( (input4.getText().toString() == " ")
|| (input4.getText().length() ==0) ||
(input5.getText().length() == 0)
|| (input5.getText().toString() == " ")){
show = new AlertDialog.Builder(mContext).setTitle("Error")
.setMessage("Some inputs are empty")
.setPositiveButton("OK", null).show();
}
else if ((input1.getText().length() != 0) &&
(input3.getText().length() ==0) && (input2.getText().length() == 0)){
double w = new Double(input3.getText().toString());
double t = new Double(input4.getText().toString());
double x = new Double(input5.getText().toString());
float e = 7;
double num = 1000*x;
double den = w*t*e;
double payback = num/den;
double money = w*t*e/1000;
Intent intent = new Intent(MainActivity.this, Power.class);
intent.putExtra("payback", payback);
intent.putExtra("money", money);
startActivity(intent);
}
else if ((input1.getText().length() == 0) && (input3.getText().length() != 0) &&
(input2.getText().length() != 0)){
double t = new
Double(input4.getText().toString());
double x = new Double(input5.getText().toString());
double v = new Double(input2.getText().toString());
double i = new Double(input3.getText().toString());
float e = 7;
double num = 1000*x;
double den = v*i*t*e;
double payback = num/den;
double money = v*i*t*e/1000;
Intent intent = new Intent(MainActivity.this, Power.class);
intent.putExtra("payback", payback);
intent.putExtra("money", money);
startActivity(intent);
}
else {
double t = new Double(input4.getText().toString());
double x = new Double(input5.getText().toString());
double v = new Double(input2.getText().toString());
double i = new Double(input3.getText().toString());
float e = 7;
double num = 1000*x;
double den = v*i*t*e;
double payback = num/den;
double money = v*i*t*e/1000;
Intent intent = new Intent(MainActivity.this, Power.class);
intent.putExtra("payback", payback);
intent.putExtra("money", money);
startActivity(intent);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Activity2
package com.example.solarcalculator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
#SuppressLint("NewApi")
public class Power extends Activity {
private double money;
private double payback;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.power);
payback = getIntent().getDoubleExtra("payback",0);
money = getIntent().getDoubleExtra("money", 0);
TextView pay = (TextView) findViewById(R.id.textView2);
String payback1 = Double.toString(payback);
pay.setText(payback1);
TextView mon = (TextView) findViewById(R.id.textView4);
String money1 = Double.toString(money);
mon.setText(money1);
}
}
I am getting java.lang.numberformatexception invalid double: "" error in logcat
anyone please help
The reason is, that "" is not a valid double. You need to test the String before or catch such exceptions
double w;
try {
w = new Double(input3.getText().toString());
} catch (NumberFormatException e) {
w = 0; // your default value
}
The value of the double depends on the language of the device.For example, for devices in french the number 0.179927 becomes 0,179927 which will always throw a NumberFormatException when parsing it to double because of the comma.
You need to change the separator from a comma to a point.
You can change the separator either by setting a locale or using the DecimalFormatSymbols.
If you want the grouping separator to be a point, you can use a european locale:
NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN);
DecimalFormat df = (DecimalFormat)nf;
Alternatively you can use the DecimalFormatSymbols class to change the symbols that appear in the formatted numbers produced by the format method. These symbols include the decimal separator, the grouping separator, the minus sign, and the percent sign, among others:
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(currentLocale);
otherSymbols.setDecimalSeparator(',');
otherSymbols.setGroupingSeparator('.');
DecimalFormat df = new DecimalFormat(formatString, otherSymbols);
You should do as below. Put it inside a try catch block
double w = new Double(input3.getText().toString());
Better to also test for .equals("") along with null.
Consider you have an afterTextChanged listener on an EditText. When you back press and clear the entered text, it'll pass != null, but still have "".
This worked for me:
double myDouble;
String myString = ((EditText) findViewById(R.id.editText1)).getText().toString();
if (myString != null && !myString.equals("")) {
myDouble = Double.valueOf(myString);
} else {
myDouble = 0;
}
Basically, you need to test whether the string that you want to convert into double is empty or not.
If it is empty, then you can just initialise it with some value and then proceed further.
For example:
if(myString.isEmpty()){
myString = ""+0.0;
}
double answer = Double.parseDouble(myString);
double latitude;
double longitude;
try {
latitude = Double.parseDouble(mApoAppointmentBeanList.get(position).getLatitude());
longitude = Double.parseDouble(mApoAppointmentBeanList.get(position).getLongitude());
String uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?q=loc:%f,%f", latitude, longitude);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(intent);
} catch (NumberFormatException e) {
// your default value
Toast.makeText(AppointmentsActivity.this, "Invalid location", Toast.LENGTH_LONG).show();
}

Unfortunately android app has stopped

I am doing a simple program for addition of two numbers which are input from EditText.
But when user clicks the button 'Click to Add' leaving the fields empty, program exits saying 'Unfortunately, program has stopped.'
Here is the code:
public class MainActivity extends Activity {
long a, b, sum;
Button add, clr;
EditText e1, e2, res;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add = (Button) findViewById(R.id.bAdd);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) throws NumberFormatException {
// TODO Auto-generated method stub
e1 = (EditText) findViewById(R.id.tv1);
String str1 = e1.getText().toString();
e2 = (EditText) findViewById(R.id.tv2);
String str2 = e2.getText().toString();
try{
a = Integer.parseInt(str1);
b = Integer.parseInt(str2);
}catch(NumberFormatException e){
res.setText("Please enter valid entries");
}
sum = a + b;
res = (EditText) findViewById(R.id.result);
res.setText("Your sum is " + sum);
}
});
clr = (Button) findViewById(R.id.bClr);
clr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) throws NumberFormatException {
// TODO Auto-generated method stub
e1.setText("");
e2.setText("");
res.setText("");
}
});
}
}
I want the app to respond 'Please enter valid entries' for blank EditText entries.
Your line:
res = (EditText) findViewById(R.id.result);
must be moved so that your res variable is initialized before you use res.setText. It's not initialized in your catch statement.
Move it to the position indicated below. You can initialise it when you do your other findViewById
e1 = (EditText) findViewById(R.id.tv1);
e2 = (EditText) findViewById(R.id.tv2);
res = (EditText) findViewById(R.id.result);
because you are getting a null text from the edit texts..so check for null first
#Override
public void onClick(View v) throws NumberFormatException {
// TODO Auto-generated method stub
e1 = (EditText) findViewById(R.id.tv1);
e2 = (EditText) findViewById(R.id.tv2);
if( e1.getText() != null && e2.getText() != null) {
String str1 = e1.getText().toString();
String str2 = e2.getText().toString();
try{
a = Integer.parseInt(str1);
b = Integer.parseInt(str2);
}catch(NumberFormatException e){
res.setText("Please enter valid entries");
}
sum = a + b;
res = (EditText) findViewById(R.id.result);
res.setText("Your sum is " + sum);
}
}
Yes.
Add these lines.
if (e1.getText().toString() == null || e2.getText().toString() == null)
{
//Show dialog
}
else
{
String str1 = e1.getText().toString();
String str2 = e2.getText().toString();
try{
a = Integer.parseInt(str1);
b = Integer.parseInt(str2);
}catch(NumberFormatException e){
res.setText("Please enter valid entries");
}
sum = a + b;
res = (EditText) findViewById(R.id.result);
res.setText("Your sum is " + sum);
}
}
And tutorial for any help on alert dialog
Instead of catching NumberFormatException you can just catch any Exception in try catch block .Please post the Log Cat Error you are getting.

Android OutputStreamWriter not creating file

I am trying to write data from EditText fields to a text file. I have verified that the data is being captured for output in an EditText field that I populate after clicking the Add button. The program runs successfully in the Emulator, but no output file is created. I have added uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" to the Android Manifest xml file. LogCat & Console do not show any errors. I have tried several different methods after reseaching examples here, but no luck. Can anyone point out my issue? Thanks in advance for your help.
package john.BRprogram;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.EditText;
//import android.graphics.Color;
import java.io.OutputStreamWriter;
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class BRprogramActivity extends Activity implements OnItemSelectedListener {
private static final String TAG = null;
//
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//
Button addButton;
Button editButton;
Button sendButton;
//
Spinner array_spinner;
//
// activate soft Keyboard
this.getWindow().setSoftInputMode
(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
//
EditText myCustomer = (EditText)findViewById(R.id.editText1);
myCustomer.setText("");
//
EditText myQuantity = (EditText)findViewById(R.id.editText2);
myQuantity.setText("");
//
EditText myPrice = (EditText)findViewById(R.id.editText3);
myPrice.setText("");
//
// .csv comma separated values file
//
try {
Scanner scanner = new Scanner(getResources().openRawResource(R.raw.brdata));
//
List<String> list = new ArrayList<String>();
while (scanner.hasNext()) {
String data = (scanner.next()); //read data record
String [] values = data.split(","); //parse data to fields
// String [] values = data.split(",(?=([^\"]\"[^\"]\")[^\"]$)");
if(values.length != 3)
Log.v("Example", "Malformed row: " + data);
else
list.add(values[0] + " " + values[1] + " $" + values[2]);
}
//
array_spinner = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this,android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
array_spinner.setAdapter(adapter);
array_spinner.setOnItemSelectedListener((OnItemSelectedListener) this);
//
scanner.close();
//
} catch (Exception e) {
Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
}
//
addButton = (Button) findViewById(R.id.addbutton);
addButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//
// get customer number,itemnumber,quantity,price
//
String writeCustomer = ((EditText) findViewById(R.id.editText1)).getText().toString().trim();
// itemNumber from list selection
String writeQuantity = ((EditText) findViewById(R.id.editText2)).getText().toString().trim();
String writePrice = ((EditText) findViewById(R.id.editText3)).getText().toString().trim();
//
String newRecord = writeCustomer + "," + writeQuantity + "," + writePrice;
EditText myString = (EditText)findViewById(R.id.editText4);
myString.setText(newRecord);
//
// write seq to output file
//
try {
OutputStreamWriter out = new OutputStreamWriter(openFileOutput("broutput.txt",0));
out.write(newRecord);
out.close();
}catch (Exception e){
Log.v("test", "record written");
}
//
EditText myQuantity = (EditText)findViewById(R.id.editText2);
myQuantity.setText("");
//
EditText myPrice = (EditText)findViewById(R.id.editText3);
myPrice.setText("");
Log.v("test", "ADD button clicked");
}
});
//
editButton = (Button) findViewById(R.id.editbutton);
editButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
Log.v("test", "EDIT button clicked");
}
});
//
sendButton = (Button) findViewById(R.id.sendbutton);
sendButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//
EditText myCustomer = (EditText)findViewById(R.id.editText1);
myCustomer.setText("");
//
EditText myQuantity = (EditText)findViewById(R.id.editText2);
myQuantity.setText("");
//
EditText myPrice = (EditText)findViewById(R.id.editText3);
myPrice.setText("");
Log.v("test", "SEND button clicked");
}
});
}
// *** http://www.youtube.com/watch?v=Pfasw0bbe_4 ***
//
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
//
String selection = parent.getItemAtPosition(position).toString();
String [] priceField = selection.split("\\$"); //parse price field
String [] item = selection.split("_"); //parse item number
String itemNumber = item[0];
//
EditText myQuantity = (EditText)findViewById(R.id.editText2);
myQuantity.setText("");
//
EditText myPrice = (EditText)findViewById(R.id.editText3);
myPrice.setText(priceField[1]);
}
//
public void onNothingSelected(AdapterView<?> arg0) {
//nothing here
}
}
Looks like you need to create and/or specify the directory where you wish to save the file. I didn't see that anywhere in your code. It might look something like this:
if (Environment.getExternalStorageState() == null) {
directory = new File(Environment.getDataDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(Environment.getDataDirectory()
+ "/Robotium-Screenshots/");
/*
* this checks to see if there are any previous test photo files
* if there are any photos, they are deleted for the sake of
* memory
*/
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length != 0) {
for (int ii = 0; ii <= dirFiles.length; ii++) {
dirFiles[ii].delete();
}
}
}
// if no directory exists, create new directory
if (!directory.exists()) {
directory.mkdir();
}
// if phone DOES have sd card
} else if (Environment.getExternalStorageState() != null) {
// search for directory on SD card
directory = new File(Environment.getExternalStorageDirectory()
+ "/RobotiumTestLog/");
photoDirectory = new File(
Environment.getExternalStorageDirectory()
+ "/Robotium-Screenshots/");
if (photoDirectory.exists()) {
File[] dirFiles = photoDirectory.listFiles();
if (dirFiles.length > 0) {
for (int ii = 0; ii < dirFiles.length; ii++) {
dirFiles[ii].delete();
}
dirFiles = null;
}
}
// if no directory exists, create new directory to store test
// results
if (!directory.exists()) {
directory.mkdir();
}
}
When you save data from your app, you have to remember that it is running on the Android, and not your computer, so all data is going to be written to your Android, not your comp. You have to pull the data after it is written to view it. Make sure you that you created a local directory on your device and make sure you check for an SD card. The code I listed will show you how to do everything you need.
Hope this helps!
I've actually experienced a problem like this; everything seemed fine, but my code wasn't working. My problem was the characters in the file name I was writing. For example, I tried writing the file name my_file - date 07/11/2012. This caused problems because it treated each / as a cue to begin a new directory! For this reason, I discovered I could not have any / (or :, for some reason) in my file names. Would this be your problem?
If this is your problem, then you could do what I did: perform a newRecord.replace('/', '-'); to replace all / in your file name with a - (if you are fine with having -'s instead).
On a side note, why are you logging "record written" in your the catch of your try/catch statement? If it catches a problem, doesn't that mean it wasn't written?

Categories

Resources