Alert Dialog not popping right. Button causing exception. Unsure why - android

Nearly everything works in a program I've been working on. As I make changes in the UI, everything is set correctly. For reasons I can't figure out, when I hit the enter button of my main UI the app force closes with an exception. From the log...
java.lang.IllegalStateException: Could not find a method enterMood(View) in the activity class com.loch.meaptracker.MainActivity for onClick handler on view class android.widget.Button with id 'enterButtonID'
Here's the program code. Eclipse doesn't flag anything for either errors or warnings. I'm at a bit of a loss and pretty burnt out looking at this. Any help would be greatly appreciated.
package com.loch.meaptracker;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TimePicker;
public class MainActivity extends Activity implements OnSeekBarChangeListener {
private SeekBar happyBar, energyBar, anxietyBar, painBar;
private EditText noteField;
private DatePicker dPick;
private TimePicker tPick;
#SuppressWarnings("unused")
private Button enterButton;
private int happyValue = 4, energyValue = 4, anxietyValue = 4,
painValue = 4;
private static final String TAG = "heapApp";
private String Mood = "Blah";
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// bars
happyBar = (SeekBar) findViewById(R.id.happinessBarID);
happyBar.setOnSeekBarChangeListener(this);
energyBar = (SeekBar) findViewById(R.id.energyBarID);
energyBar.setOnSeekBarChangeListener(this);
anxietyBar = (SeekBar) findViewById(R.id.anxietyBarID);
anxietyBar.setOnSeekBarChangeListener(this);
painBar = (SeekBar) findViewById(R.id.painBarID);
painBar.setOnSeekBarChangeListener(this);
// end bars
dPick = (DatePicker) findViewById(R.id.datePicker1);
tPick = (TimePicker) findViewById(R.id.timePicker1);
noteField = (EditText) findViewById(R.id.noteTextFieldID);
enterButton = (Button) findViewById(R.id.enterButtonID);
} catch (Exception onCreateException) {
Log.e(TAG, "Exception received", onCreateException);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
// Bar listener methods
#Override
public void onProgressChanged(SeekBar arg0, int barValue, boolean hFromUser) {
try {
switch (arg0.getId()) {
case R.id.happinessBarID:
happyValue = barValue + 1;
break;
case R.id.energyBarID:
energyValue = barValue + 1;
break;
case R.id.anxietyBarID:
anxietyValue = barValue + 1;
break;
case R.id.painBarID:
painValue = barValue + 1;
break;
}
String debugBarValue = "Happy is " + happyValue + ", Energy is "
+ energyValue + ", Anxiety is " + anxietyValue
+ ", Pain is " + painValue + ".";
System.out.println(debugBarValue);
} catch (Exception BarValueException) {
Log.e(TAG, "Exception received", BarValueException);
}
}
#Override
public void onStartTrackingTouch(SeekBar happyBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar happyBar) {
// TODO Auto-generated method stub
}
// end Bar listener methods
// Enter Button listener Method
public void dialogPop(View v) {
try {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set Title
alertDialogBuilder.setTitle("title");
// set dialog message
alertDialogBuilder.setMessage("You entered: " + getMood())
.setCancelable(false).setPositiveButton("Okay",
// When Okay button clicked the write mood string to file
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
try {
// This is the string that should be
// written to file
String data = getMood();
// This is the file that should be
// written to
File heapFile = new File("heapFile.csv");
// if file doesn't exists, then create
// it
if (!heapFile.exists()) {
heapFile.createNewFile();
}
// true = append file
FileWriter heapFileWritter = new FileWriter(
heapFile.getName(), true);
BufferedWriter heapBufferWritter = new BufferedWriter(
heapFileWritter);
heapBufferWritter.write(data);
heapBufferWritter.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
})
// If they press either the cancel button or the back button
// on their device (Same thing) then close the dialog and
// give the user a chance to change what they've entered
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
} catch (Exception buttonListenerException) {
Log.e(TAG, "Exception received", buttonListenerException);
}
return;
}
public String getMood() {
try {
int month = dPick.getMonth();
int day = dPick.getDayOfMonth();
int year = dPick.getYear();
int minute = tPick.getCurrentMinute();
String moodAntePost = "AM";
boolean hourType = tPick.is24HourView();
int moodHour = tPick.getCurrentHour();
if (hourType == false && moodHour > 12) {
moodHour = (moodHour - 12);
moodAntePost = "PM";
} else if (hourType == false && moodHour <= 0) {
moodHour = 12;
} else {
}
String noteText = noteField.getText().toString();
Mood = "Happiness," + happyValue + ",Energy," + energyValue
+ ",Anxiety," + anxietyValue + ",Pain," + painValue
+ ",Date," + month + "/" + day + "/" + year + ",Time,"
+ moodHour + ":" + minute + "," + moodAntePost + ",Note,"
+ noteText;
System.out.println(Mood);
} catch (Exception getMoodException) {
Log.e(TAG, "Exception received", getMoodException);
}
return Mood;
}
}

Please check the XML code . i think there in tag of your XML there is one attribute you have added android:onClick="enterMood".... try removing it and running it
use
android:onClick="dialogPop" instead

Your click handler is not in the right format. It needs to include a view parameter for the XML click handler to work properly.
public void getMood(View view){
}

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.

ProgressDialog.show() is not showing the progress dialog

I am trying to display a progress dialog inside a fragment.But progressbar.show() do not have any effect.However,I noticed a strange behaviour,if i call showPopUp() method twice,it does show the progress dialog,but unable to dismiss().
package com.snapbizz.snapdashboard.Tabs.v1;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.snapbizz.snapdashboard.Core.v1.SalesData;
import com.snapbizz.snapdashboard.R;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class DashBoardSalesTab extends Fragment {
LinearLayout salesListContainer, salesBarConatainer;
LayoutInflater layoutInflater;
SalesData salesData;
ProgressDialog progressDialog;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.sales_page_layout, container, false);
return rootView;
}
public void showPopUp() {
progressDialog = new ProgressDialog(getContext(), ProgressDialog.THEME_HOLO_LIGHT);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("loading the page...");
progressDialog.setProgressNumberFormat(null);
progressDialog.setProgressPercentFormat(null);
progressDialog.setIndeterminate(true);
progressDialog.show();
}
public void synchronizeScrollers() {
getActivity().findViewById(R.id.page_scroller).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
getActivity().findViewById(R.id.table_scroller).getParent()
.requestDisallowInterceptTouchEvent(true);
return false;
}
});
getActivity().findViewById(R.id.table_scroller).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.getParent().requestDisallowInterceptTouchEvent(true);
return false;
}
});
}
public void renderSalesGraph(List<String[]> values, Float totalSumY) throws Exception {
salesBarConatainer.removeAllViews();
for (String[] value : values) {
View barView = layoutInflater.inflate(R.layout.bar_char_item_layout, salesBarConatainer, false);
float sumOfSalesForTheDay = Float.parseFloat((value[0] == null) ? "0" : value[0]);
float weightofBar = sumOfSalesForTheDay / totalSumY;
barView.findViewById(R.id.bar_y).setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, weightofBar));
((TextView) barView.findViewById(R.id.value_y)).setText(
(sumOfSalesForTheDay == 0.0f ? "" :
getActivity().getResources().getString(R.string.rupee_symbol) + sumOfSalesForTheDay + "")
);
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy/MM/dd");
SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MMM-yyyy");
Date renderingDate = inputFormat.parse(value[2]);
String[] date = outputFormat.format(renderingDate).split("-");
((TextView) barView.findViewById(R.id.value_x_date)).setText(date[0] + " " + date[1]);
((TextView) barView.findViewById(R.id.value_x_year)).setText(date[2]);
salesBarConatainer.addView(barView);
}
}
public void renderSalesGraphForMonths(List<String[]> values, Float totalSumY) throws Exception {
LinearLayout salesBarConatainer = (LinearLayout) getActivity().findViewById(R.id.bars_container);
salesBarConatainer.removeAllViews();
for (String[] value : values) {
View barView = layoutInflater.inflate(R.layout.bar_char_item_layout, salesBarConatainer, false);
float sumOfSalesForTheDay = Float.parseFloat((value[0] == null) ? "0" : value[0]);
float weightofBar = sumOfSalesForTheDay / totalSumY;
barView.findViewById(R.id.bar_y).setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0, weightofBar));
((TextView) barView.findViewById(R.id.value_y)).setText(
(sumOfSalesForTheDay == 0.0f ? "" :
getActivity().getResources().getString(R.string.rupee_symbol) + sumOfSalesForTheDay + "")
);
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy/MM");
SimpleDateFormat outputFormat = new SimpleDateFormat("MMM-yyyy");
Date renderingDate = inputFormat.parse(value[2]);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, renderingDate.getMonth());
cal.set(Calendar.DAY_OF_MONTH, 1);
barView.setOnClickListener(new MonthBarClickListener(cal));
String[] date = outputFormat.format(renderingDate).split("-");
((TextView) barView.findViewById(R.id.value_x_date)).setText(date[0]);
((TextView) barView.findViewById(R.id.value_x_year)).setText(date[1]);
salesBarConatainer.addView(barView);
}
}
public String[] addTOSalesTable(String date, boolean header) throws Exception {
List<String[]> values = salesData.getSalesTableData(date);
String[] value = values.get(0);
String[] newValue = {value[0], value[1], date};
String totalSales = (value[0] == null) ? "0" : value[0];
String totalCredit = (value[1] == null) ? "0" : value[1];
String totalCash = (Float.parseFloat(totalSales) - Float.parseFloat(totalCredit)) + "";
String rupeeSymbol = getActivity().getResources().getString(R.string.rupee_symbol);
if (!header) {
View salesRow = layoutInflater.inflate(R.layout.sales_page_table_row_layout, salesListContainer, false);
((TextView) (salesRow.findViewById(R.id.sale_date))).
setText(date);
((TextView) (salesRow.findViewById(R.id.sales_total_sale))).
setText(rupeeSymbol + " " + totalSales);
((TextView) (salesRow.findViewById(R.id.sales_total_cash))).
setText(rupeeSymbol + " " + totalCash);
((TextView) (salesRow.findViewById(R.id.sales_total_credit))).
setText(rupeeSymbol + " " + totalCredit);
((TextView) (salesRow.findViewById(R.id.sales_ttoal_coupon))).
setText(rupeeSymbol + " " + "0");
if (salesListContainer.getChildCount() % 2 != 0) {
salesRow.setBackgroundColor(getResources().getColor(R.color.table_row_alternate_color));
}
salesListContainer.addView(salesRow);
} else {
((TextView) (getActivity().findViewById(R.id.sales_header_total_sales))).
setText(rupeeSymbol + " " + totalSales);
((TextView) (getActivity().findViewById(R.id.sales_header_total_cash))).
setText(rupeeSymbol + " " + totalCash);
((TextView) (getActivity().findViewById(R.id.sales_header_total_credit))).
setText(rupeeSymbol + " " + totalCredit);
((TextView) (getActivity().findViewById(R.id.sales_header_total_coupon))).
setText(rupeeSymbol + " " + "0");
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date presentDate = new Date();
((TextView) (getActivity().findViewById(R.id.sales_header_day))).
setText(date.contentEquals(dateFormat.format(presentDate)) ? "Today" : date);
}
return newValue;
}
public void getMonths() throws Exception {
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM");
List<String[]> values = new ArrayList<>();
float totalSumY = 0.0f;
for (int i = 0; i < 12; i++) {
cal.add(Calendar.MONTH, (i == 0) ? 0 : -1);
String date = dateFormat.format(cal.getTime());
String[] value = salesData.getSalesDataForMonth(date);
String[] newValue = {value[0] == null ? "0" : value[0], value[1] == null ? "0" : value[1], date};
totalSumY += Float.parseFloat(value[0] == null ? "0" : value[0]);
values.add(newValue);
}
renderSalesGraphForMonths(values, totalSumY);
}
public void initChart() {
FrameLayout dayButton = (FrameLayout) getActivity().findViewById(R.id.day_button);
FrameLayout monthButton = (FrameLayout) getActivity().findViewById(R.id.month_button);
dayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
((TextView) getActivity().findViewById(R.id.button_day_text)).setTextColor(
getResources().getColor(R.color.dark_darkblue)
);
((TextView) getActivity().findViewById(R.id.button_day_text)).
setBackground(getResources().getDrawable(R.drawable.button_border_active));
((TextView) getActivity().findViewById(R.id.button_month_text)).setTextColor(
getResources().getColor(R.color.default_text_color)
);
((TextView) getActivity().findViewById(R.id.button_month_text)).
setBackground(getResources().getDrawable(R.drawable.button_border));
generateTablesRows(Calendar.getInstance(), 60, -1);
} catch (Exception e) {
e.printStackTrace();
}
}
});
monthButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
((TextView) getActivity().findViewById(R.id.button_month_text)).setTextColor(
getResources().getColor(R.color.dark_darkblue)
);
((TextView) getActivity().findViewById(R.id.button_month_text)).
setBackground(getResources().getDrawable(R.drawable.button_border_active));
((TextView) getActivity().findViewById(R.id.button_day_text)).setTextColor(
getResources().getColor(R.color.default_text_color)
);
((TextView) getActivity().findViewById(R.id.button_day_text)).
setBackground(getResources().getDrawable(R.drawable.button_border));
getMonths();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void generateTablesRows(Calendar cal, int limit, int increment) throws Exception {
salesListContainer.removeAllViews();
float totalSumY = 0.0f;
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
List<String[]> barGraphValues = new ArrayList<>();
for (int i = 0; i < limit; i++) {
cal.add(Calendar.DATE, (i == 0) ? 0 : increment);
String date = dateFormat.format(cal.getTime());
String[] value = addTOSalesTable(date, (i == 0) ? true : false);
totalSumY += Float.parseFloat((value[0] == null) ? "1" : value[0]);
barGraphValues.add(value);
}
renderSalesGraph(barGraphValues, totalSumY);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
showPopUp();
layoutInflater = LayoutInflater.from(getContext());
salesListContainer = (LinearLayout) (getActivity().findViewById(R.id.sales_list_container));
salesListContainer.removeAllViews();
salesBarConatainer = (LinearLayout) getActivity().findViewById(R.id.bars_container);
salesBarConatainer.removeAllViews();
new SalesTabLoader().execute();
}
public class MonthBarClickListener implements View.OnClickListener {
Calendar cal;
public MonthBarClickListener(Calendar cal) {
this.cal = cal;
}
#Override
public void onClick(View v) {
try {
//new SalesAsyncTask(cal).execute(cal.getActualMaximum(Calendar.DAY_OF_MONTH),1);
generateTablesRows(cal, cal.getActualMaximum(Calendar.DAY_OF_MONTH), 1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class SalesTabLoader extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
salesData = new SalesData(getContext());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
try {
initChart();
generateTablesRows(Calendar.getInstance(), 60, -1);
} catch (Exception e) {
e.printStackTrace();
} finally {
synchronizeScrollers();
progressDialog.dismiss();
}
}
}
}
Try like this :
progressDialog = new ProgressDialog(getActivity());
And if you wish to customize your dialog and put self created Layout in it.
/**
* Created by vivek on 18/10/16.
*/
public class CustomDialog {
private static Dialog dialog;
private static Context context;
public CustomDialog(Context context) {
this.context = context;
}
/**
* Comman progress dialog ... initiates with this
*
* #param message
* #param title
*/
public static void showProgressDialog(Context context, String title, String message) {
if (dialog == null)
{
dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_loader);
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
}
public static boolean isProgressDialogRunning() {
if (dialog != null && dialog.isShowing()) {
return true;
} else return false;
}
/**
* Dismiss comman progress dialog
*/
public static void dismissProgressDialog() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
dialog = null;
}
}
} // End of main class over here ...
Replace this:-
progressDialog = new ProgressDialog(getContext(), ProgressDialog.THEME_HOLO_LIGHT);
with
progressDialog = new ProgressDialog(getActivity());
May be. you are showing two progressdialog and both of that progressbar on screen.. but when you dismiss your progressbar at that time the previous one is override by other one before you dismiss first one .. so the firstone is always in screen. that's the issue.
I tried everything.But none of the answers solved the issue.However,i solved it by overriding onResume() method in the fragment.
Thanks All.

Android Shared Preferences resume game button not working

I am creating a game app, which needs to allow the player to save and resume their position.
The save works fine, storing the room position, it retrieves the room position fine when clicking the "resume" button but doesn't take the player to the saved room position, it just starts the game from the beginning.
I think it maybe to do with this code, but after 8 hours of research, I still have no idea how to alter it:-
Intent value = new Intent(MainMenu.this, MainActivity.class);
startActivity(value);
Please help, thanks!
package com.example.gameversion2;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainMenu extends AppCompatActivity {
Button play;
Button resume;
Button exit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
resume = (Button) findViewById(R.id.resume);
resume.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
SharedPreferences sp = getSharedPreferences("SAVEPOS", Context.MODE_PRIVATE);
//Load the Editor NOTE: Remember to COMMIT the changes
//Retrieve the Values written to shared preferences
int Value = sp.getInt("save", -1);
Log.w("LOG_TAG", "value: " + Value);
Intent value = new Intent(MainMenu.this, MainActivity.class);
startActivity(value);
}
});
play = (Button) findViewById(R.id.play);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainMenu.this, MainActivity.class);
startActivity(intent);
}
});
exit = (Button) findViewById(R.id.exit);
exit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});//protected void onCreate(Bundle savedInstanceState)
}
}
This is the MainActivity
package com.example.gameversion2;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.XmlResourceParser;
import android.graphics.Point;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
static final int NO_EXIT = -1;
static final int NUM_OF_ROOMS = 21;
Room[] countries;
Button north;
Button east;
Button south;
Button west;
Button save;
Button exit;
TextView textview;
ImageView flagimg;
int playerPos = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initTheCountries();
readXMLFile();
displayRooms();
setupControls();
setupImage();
// startGame();
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
Log.w("TAG", "width = " + width + " height = " + height);
//Toast.makeText(getApplicationContext(), "w = " + width + " height = "+ height, Toast.LENGTH_LONG).show();
textview.setText(countries[playerPos].getDescription());
setupDirectionButtons();
} // protected void onCreate(Bundle savedInstanceState) {
// private void startGame() {
// Variables
//question = S.LoadGame();
//boolean running = true;
// textview.setText("Welcome to Escape The Country!");
// }
private void setupImage() {
ImageView imagePlayer;
ImageView imageRedbull;
imagePlayer = (ImageView)findViewById(R.id.imagePlayer);
imageRedbull = (ImageView)findViewById(R.id.imageRedbull);
imagePlayer.setImageResource(R.drawable.player);
imageRedbull.setImageResource(R.drawable.redbull);
}
public void setupDirectionButtons()
{
// north
if (countries[playerPos].getNorth() == -1 )
{
north.setEnabled(false);
}
else
{
north.setEnabled(true);
}
// east
if (countries[playerPos].getEast() == -1 )
{
east.setEnabled(false);
}
else
{
east.setEnabled(true);
}
// south
if (countries[playerPos].getSouth() == -1 )
{
south.setEnabled(false);
}
else
{
south.setEnabled(true);
}
// west
if (countries[playerPos].getWest() == -1 )
{
west.setEnabled(false);
}
else
{
west.setEnabled(true);
}
} // public void setupDirectionButtons()
public void setupControls()
{
north = (Button)findViewById(R.id.north);
east = (Button)findViewById(R.id.east);
south = (Button)findViewById(R.id.south);
west = (Button)findViewById(R.id.west);
textview = (TextView)findViewById(R.id.textView);
flagimg = (ImageView)findViewById(R.id.flagimg);
save = (Button)findViewById(R.id.saveButton);
save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
SharedPreferences sp = getSharedPreferences("SAVEPOS", Context.MODE_PRIVATE);
//Load the Editor NOTE: Remember to COMMIT the changes
SharedPreferences.Editor e = sp.edit();
e.putInt("save", playerPos);
e.commit();
//Retrieve the Values written to shared preferences
int Value = sp.getInt("save", -1);
Log.w("LOG_TAG", "value: " + Value);
//imageview.setX(imageview.getX() + 10);
}
});
north.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
playerPos = countries[playerPos].getNorth();
textview.setText( countries[playerPos].getDescription());
setupDirectionButtons();
UpdateImage();
}
});
east.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
playerPos = countries[playerPos].getEast();
textview.setText( countries[playerPos].getDescription());
setupDirectionButtons();
UpdateImage();
}
});
south.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
playerPos = countries[playerPos].getSouth();
textview.setText( countries[playerPos].getDescription());
setupDirectionButtons();
UpdateImage();
}
});
west.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
playerPos = countries[playerPos].getWest();
textview.setText( countries[playerPos].getDescription());
setupDirectionButtons();
UpdateImage();
}
});
}
public void UpdateImage()
{
switch (playerPos)
{
case 0:
flagimg.setImageResource(R.drawable.canada);
break;
case 1 :
flagimg.setImageResource(R.drawable.norway);
break;
case 2 :
flagimg.setImageResource(R.drawable.sweden);
break;
case 3 :
flagimg.setImageResource(R.drawable.switzerland);
break;
case 4:
flagimg.setImageResource(R.drawable.australia);
break;
case 5 :
flagimg.setImageResource(R.drawable.finland);
break;
case 6 :
flagimg.setImageResource(R.drawable.newzealand);
break;
case 7 :
flagimg.setImageResource(R.drawable.denmark);
break;
case 8:
flagimg.setImageResource(R.drawable.netherland);
break;
case 9 :
flagimg.setImageResource(R.drawable.belgium);
break;
case 10 :
flagimg.setImageResource(R.drawable.ireland);
break;
case 11 :
flagimg.setImageResource(R.drawable.austria);
break;
case 12:
flagimg.setImageResource(R.drawable.uk);
break;
case 13 :
flagimg.setImageResource(R.drawable.italy);
break;
case 14 :
flagimg.setImageResource(R.drawable.germany);
break;
case 15 :
flagimg.setImageResource(R.drawable.japan);
break;
case 16 :
flagimg.setImageResource(R.drawable.spain);
break;
case 17:
flagimg.setImageResource(R.drawable.portugal);
break;
case 18 :
flagimg.setImageResource(R.drawable.france);
break;
case 19 :
flagimg.setImageResource(R.drawable.canada);
break;
case 20 :
flagimg.setImageResource(R.drawable.canada);
break;
}
}
public void initTheCountries() {
countries = new Room[NUM_OF_ROOMS];
for (int pos = 0; pos < NUM_OF_ROOMS; pos++)
{
countries[pos] = new Room();
}
} // public static void initTheCountries()
public void displayRooms() {
Log.w("display ROOM", "**************** start of display rooms ********************************");
for (int pos = 0; pos < NUM_OF_ROOMS; pos++)
{
Log.w("display ROOM", "North = " + countries[pos].getNorth());
Log.w("display ROOM", "East = " + countries[pos].getEast());
Log.w("display ROOM", "West = " + countries[pos].getWest());
Log.w("display ROOM", "South = " + countries[pos].getSouth());
Log.w("display ROOM", "Description = " + countries[pos].getDescription());
}
Log.w("display ROOM", "**************** end of display rooms **********************************");
} // public void displayRooms() {
public void readXMLFile() {
int pos = 0; // May be use this variable, to keep track of what position of the array of Room Objects.
try {
XmlResourceParser xpp = getResources().getXml(R.xml.countries);
xpp.next();
int eventType = xpp.getEventType();
int room_count = 0;
String elemtext = null;
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
String elemName = xpp.getName();
if (elemName.equals("countries")) {
String titleAttr = xpp.getAttributeValue(null,"title");
String authorAttr = xpp.getAttributeValue(null,"author");
} // if (elemName.equals("countries"))
if (elemName.equals("room")) {
room_count = room_count + 1;
}
if (elemName.equals("north")) {
elemtext = "north";
}
if (elemName.equals("east")) {
elemtext = "east";
}
if (elemName.equals("south")) {
elemtext = "south";
}
if (elemName.equals("west")) {
elemtext = "west";
}
if (elemName.equals("description")) {
elemtext = "description";
}
} // if (eventType == XmlPullParser.START_TAG)
// You will need to add code in this section to read each element of the XML file
// And then store the value in the current Room Object.
// NOTE: This method initTheCountries() creates and array of Room Objects, ready to be populated!
// As you can see at the moment the data/text is displayed in the LogCat Window
// Hint: xpp.getText()
else if (eventType == XmlPullParser.TEXT) {
if (elemtext.equals("north")) {
Log.w("ROOM", "north = " + xpp.getText());
countries[room_count-1].setNorth( Integer.valueOf(xpp.getText()));
}
else if (elemtext.equals("east")) {
Log.w("ROOM", "east = " + xpp.getText());
countries[room_count-1].setEast(Integer.valueOf(xpp.getText()));
}
else if (elemtext.equals("south")) {
Log.w("ROOM", "south = " + xpp.getText());
countries[room_count-1].setSouth(Integer.valueOf(xpp.getText()));
}
else if (elemtext.equals("west")) {
Log.w("ROOM", "west = " + xpp.getText());
countries[room_count-1].setWest(Integer.valueOf(xpp.getText()));
}
else if (elemtext.equals("description")) {
Log.w("ROOM", "description = " + xpp.getText());
countries[room_count-1].setDescription( xpp.getText() );
}
} // else if (eventType == XmlPullParser.TEXT)
eventType = xpp.next();
} // while (eventType != XmlPullParser.END_DOCUMENT)
} // try
catch (XmlPullParserException e) {
}
catch (IOException e) {
}
exit = (Button) findViewById(R.id.exit);
exit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
} // public void readXMLFile()
} // public class MainActivity extends AppCompatActivity {
myapp
You are not passing the value to another activity.
Set it to intent like this:
int Value = sp.getInt("save", -1);
Log.w("LOG_TAG", "value: " + Value);
Intent value = new Intent(MainMenu.this, MainActivity.class);
value.putExtra("save", Value);
startActivity(value);
And in your MainActivity take the value using getIntent().getIntExtra().
Put it in your onCreate() method, after setContentView():
playerPos = getIntent().getIntExtra("save", 0);
and then use it to set player position.

If file does not exist, create it and write string to it. If it does then append string to it. Isn't working right

Okay, I read a lot and thought I had this worked out but apparently not. What I'm trying to do is check to see if a file exists (in this case heapFile.csv) and if it doesn't to create it and then write a string to it. If the file does exist, then I want to append the string to the file. I get no errors when I run this though I do get a warning saying that it can't create the file although it actually does do so. However it's not writing the string to the file in either case. I'm probably just not using the right syntax or something but after staring at this for weeks I can't see the forest for the trees and find the problem. Aside from this one issue my program is working fine and if I can just get this working I can FINALLY finish this. Any help is incredibly appreciated.
Here's the java file. I think it's clear where the file creation/writing bit is.
package com.loch.meaptracker;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import com.google.ads.*;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TimePicker;
public class MainActivity extends Activity implements OnSeekBarChangeListener {
private SeekBar happyBar, energyBar, anxietyBar, painBar;
private EditText noteField;
private DatePicker dPick;
private TimePicker tPick;
#SuppressWarnings("unused")
private Button enterButton;
private int happyValue = 4, energyValue = 4, anxietyValue = 4,
painValue = 4;
private static final String TAG = "heapApp";
private String Mood = "Blah";
private AdView adView;
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adView
adView = new AdView (this, AdSize.BANNER, "a15138b1a7adad2");
// Lookup your RelativeLayout assuming it's been given the attribute android:id="#+id/AdRelativeLayout
RelativeLayout layout = (RelativeLayout)findViewById(R.id.AdRelativeLayout);
// Add the AdView to it
layout.addView(adView);
// Initiate a generic request to load it with an ad
adView.loadAd(new AdRequest());
// bars
happyBar = (SeekBar) findViewById(R.id.happinessBarID);
happyBar.setOnSeekBarChangeListener(this);
energyBar = (SeekBar) findViewById(R.id.energyBarID);
energyBar.setOnSeekBarChangeListener(this);
anxietyBar = (SeekBar) findViewById(R.id.anxietyBarID);
anxietyBar.setOnSeekBarChangeListener(this);
painBar = (SeekBar) findViewById(R.id.painBarID);
painBar.setOnSeekBarChangeListener(this);
// end bars
dPick = (DatePicker) findViewById(R.id.datePicker1);
tPick = (TimePicker) findViewById(R.id.timePicker1);
noteField = (EditText) findViewById(R.id.noteTextFieldID);
enterButton = (Button) findViewById(R.id.enterButtonID);
} catch (Exception onCreateException) {
Log.e(TAG, "Exception received", onCreateException);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
// Bar listener methods
#Override
public void onProgressChanged(SeekBar arg0, int barValue, boolean hFromUser) {
try {
switch (arg0.getId()) {
case R.id.happinessBarID:
happyValue = barValue + 1;
break;
case R.id.energyBarID:
energyValue = barValue + 1;
break;
case R.id.anxietyBarID:
anxietyValue = barValue + 1;
break;
case R.id.painBarID:
painValue = barValue + 1;
break;
}
String debugBarValue = "Happy is " + happyValue + ", Energy is "
+ energyValue + ", Anxiety is " + anxietyValue
+ ", Pain is " + painValue + ".";
System.out.println(debugBarValue);
} catch (Exception BarValueException) {
Log.e(TAG, "Exception received", BarValueException);
}
}
#Override
public void onStartTrackingTouch(SeekBar happyBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar happyBar) {
// TODO Auto-generated method stub
}
// end Bar listener methods
// Enter Button listener Method
public void dialogPop(View v) {
try {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set Title
alertDialogBuilder.setTitle("title");
// set dialog message
alertDialogBuilder.setMessage("You entered: " + getMood())
.setCancelable(false).setPositiveButton("Okay",
// When Okay button clicked the write mood string to file
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
try {
// This is the string that should be
// written to file
String data = getMood();
// This is the file that should be
// written to
File heapFile = new File(Environment.getExternalStorageDirectory(), "heapFile.csv");
// if file doesn't exists, then create
// it
if (!heapFile.exists()) {
heapFile.createNewFile();
FileWriter heapFileWritter = new FileWriter(
heapFile.getName(), true);
BufferedWriter heapBufferWritter = new BufferedWriter(
heapFileWritter);
heapBufferWritter.write(data);
heapBufferWritter.close();
System.out.println("Done");
}
// true = append file
FileWriter heapFileWritter = new FileWriter(
heapFile.getName(), true);
BufferedWriter heapBufferWritter = new BufferedWriter(
heapFileWritter);
heapBufferWritter.write(data);
heapBufferWritter.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
})
// If they press either the cancel button or the back button
// on their device (Same thing) then close the dialog and
// give the user a chance to change what they've entered
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
} catch (Exception buttonListenerException) {
Log.e(TAG, "Exception received", buttonListenerException);
}
return;
}
public String getMood() {
try {
int month = dPick.getMonth();
int day = dPick.getDayOfMonth();
int year = dPick.getYear();
int minute = tPick.getCurrentMinute();
String moodAntePost = "AM";
boolean hourType = tPick.is24HourView();
int moodHour = tPick.getCurrentHour();
if (hourType == false && moodHour > 12) {
moodHour = (moodHour - 12);
moodAntePost = "PM";
} else if (hourType == false && moodHour <= 0) {
moodHour = 12;
} else {
}
String noteText = noteField.getText().toString();
Mood = "Happiness," + happyValue + ",Energy," + energyValue
+ ",Anxiety," + anxietyValue + ",Pain," + painValue
+ ",Date," + month + "/" + day + "/" + year + ",Time,"
+ moodHour + ":" + minute + "," + moodAntePost + ",Note,"
+ noteText;
System.out.println(Mood);
} catch (Exception getMoodException) {
Log.e(TAG, "Exception received", getMoodException);
}
return Mood;
}
}
Edited my question to include the manifest so you can see the permissions I've got. I think it's right but I'm not certain...
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.loch.meaptracker"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.loch.meaptracker.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.google.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
</application>
</manifest>
use this:
String file = heapFile.getAbsolutePath();
FileWriter heapFileWritter = new FileWriter(file, true);
getName() would give you just the name of the file. But you need to provide absolutepath for FileWriter.

Write or append string to a file. Getting read only file system error

First off I wanted to thank everyone for the help I've gotten on my last few questions. I've searched and done my best to figure out my latest problem but I've had no luck even after searching here. I'm trying to check to see if "heapFile.csv" exists and if it doesn't, to create the file and then write a string to it. If it does then I just want to append a string to it instead. I think what I have will do that but I keep getting an IOException along with it saying the file system is Read Only. I do have the manifest file changed to include accessing the sdcard and even used the android too to make a virtual sdcard in case that was the problem.
First here's the main activity java...
package com.loch.meaptracker;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TimePicker;
public class MainActivity extends Activity implements OnSeekBarChangeListener {
private SeekBar happyBar, energyBar, anxietyBar, painBar;
private EditText noteField;
private DatePicker dPick;
private TimePicker tPick;
#SuppressWarnings("unused")
private Button enterButton;
private int happyValue = 4, energyValue = 4, anxietyValue = 4,
painValue = 4;
private static final String TAG = "heapApp";
private String Mood = "Blah";
final Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// bars
happyBar = (SeekBar) findViewById(R.id.happinessBarID);
happyBar.setOnSeekBarChangeListener(this);
energyBar = (SeekBar) findViewById(R.id.energyBarID);
energyBar.setOnSeekBarChangeListener(this);
anxietyBar = (SeekBar) findViewById(R.id.anxietyBarID);
anxietyBar.setOnSeekBarChangeListener(this);
painBar = (SeekBar) findViewById(R.id.painBarID);
painBar.setOnSeekBarChangeListener(this);
// end bars
dPick = (DatePicker) findViewById(R.id.datePicker1);
tPick = (TimePicker) findViewById(R.id.timePicker1);
noteField = (EditText) findViewById(R.id.noteTextFieldID);
enterButton = (Button) findViewById(R.id.enterButtonID);
} catch (Exception onCreateException) {
Log.e(TAG, "Exception received", onCreateException);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
// Bar listener methods
#Override
public void onProgressChanged(SeekBar arg0, int barValue, boolean hFromUser) {
try {
switch (arg0.getId()) {
case R.id.happinessBarID:
happyValue = barValue + 1;
break;
case R.id.energyBarID:
energyValue = barValue + 1;
break;
case R.id.anxietyBarID:
anxietyValue = barValue + 1;
break;
case R.id.painBarID:
painValue = barValue + 1;
break;
}
String debugBarValue = "Happy is " + happyValue + ", Energy is "
+ energyValue + ", Anxiety is " + anxietyValue
+ ", Pain is " + painValue + ".";
System.out.println(debugBarValue);
} catch (Exception BarValueException) {
Log.e(TAG, "Exception received", BarValueException);
}
}
#Override
public void onStartTrackingTouch(SeekBar happyBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar happyBar) {
// TODO Auto-generated method stub
}
// end Bar listener methods
// Enter Button listener Method
public void dialogPop(View v) {
try {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set Title
alertDialogBuilder.setTitle("title");
// set dialog message
alertDialogBuilder.setMessage("You entered: " + getMood())
.setCancelable(false).setPositiveButton("Okay",
// When Okay button clicked the write mood string to file
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
try {
// This is the string that should be
// written to file
String data = getMood();
// This is the file that should be
// written to
File heapFile = new File(Environment.getExternalStorageDirectory(), "/heapFile.csv");
// if file doesn't exists, then create
// it
if (!heapFile.exists()) {
heapFile.createNewFile();
}
// true = append file
FileWriter heapFileWritter = new FileWriter(
heapFile.getName(), true);
BufferedWriter heapBufferWritter = new BufferedWriter(
heapFileWritter);
heapBufferWritter.write(data);
heapBufferWritter.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
})
// If they press either the cancel button or the back button
// on their device (Same thing) then close the dialog and
// give the user a chance to change what they've entered
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
} catch (Exception buttonListenerException) {
Log.e(TAG, "Exception received", buttonListenerException);
}
return;
}
public String getMood() {
try {
int month = dPick.getMonth();
int day = dPick.getDayOfMonth();
int year = dPick.getYear();
int minute = tPick.getCurrentMinute();
String moodAntePost = "AM";
boolean hourType = tPick.is24HourView();
int moodHour = tPick.getCurrentHour();
if (hourType == false && moodHour > 12) {
moodHour = (moodHour - 12);
moodAntePost = "PM";
} else if (hourType == false && moodHour <= 0) {
moodHour = 12;
} else {
}
String noteText = noteField.getText().toString();
Mood = "Happiness," + happyValue + ",Energy," + energyValue
+ ",Anxiety," + anxietyValue + ",Pain," + painValue
+ ",Date," + month + "/" + day + "/" + year + ",Time,"
+ moodHour + ":" + minute + "," + moodAntePost + ",Note,"
+ noteText;
System.out.println(Mood);
} catch (Exception getMoodException) {
Log.e(TAG, "Exception received", getMoodException);
}
return Mood;
}
}
And the Manifest...
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.loch.meaptracker"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.loch.meaptracker.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I think problem is in this line:
FileWriter heapFileWritter = new FileWriter(
heapFile.getName(), true);
instead try this:
FileWriter heapFileWritter = new FileWriter(
heapFile, true);
explanation:
heapFile.getName() refers to your file name so lets say heapFile.txt.
so when you ask FileWriter to write to this file. It doesn't know which file you are referring to. So it try to create the file. But wait! where it will create the file, as it has only the file name, not the complete path.
So even I am sure where it would think of creating the file, my guess is Root( I am not sure). Which is read-only hence the error.
public FileWriter(String fileName,
boolean append)
throws IOException
IOException - if the named file exists but is a directory rather than
a regular file, does not exist but cannot be created, or cannot be
opened for any other reason

Categories

Resources