I have a Calendar activity. When the user selects a date, I would like the TextView under the calendar to display all events the user has stored for that date. Under the TextView is a button that takes the user to the activity where they create the event. The button on the Event Creation Activity uses fileOutputStream to save a txt file containing entered information. My issue is reading that info into the TextView on the Calendar Activity. I have the code written for the read, but when I try to point it to the directory created by the fileOutput on EventCreateActivity, I get an error "EventCreateActivity is not an enclosing class." I believe it is an enclosing class, as it has nested classes, correct? What can I do here that requires the least amount of restructuring?
Here is my CalendarActivity:
public class CalendarActivity extends AppCompatActivity {
CalendarView calendar;
Button createEvent;
public static String createEventDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
calendar = (CalendarView)findViewById(R.id.calendar);
calendar.setOnDateChangeListener(new CalendarView.OnDateChangeListener(){
#Override
public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth){
createEventDate = (month+"."+dayOfMonth+"."+year);
createEvent.setText("Create Event for "+createEventDate);
File directory = EventCreateActivity.this.getFilesDir().getAbsoluteFile();
File[] dateFile = directory.listFiles();
if (dateFile.length > 0){
fillEventList();
}else{
noEventToday();
}
}
});
createEvent = (Button)findViewById(R.id.eventCreateButton);
createEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent toEventCreateActivity = new Intent(CalendarActivity.this, EventCreateActivity.class);
startActivity(toEventCreateActivity);
}
});
}
public void fillEventList (){
TextView eventList = (TextView)findViewById(R.id.eventList);
try {
String message = createEventDate;
FileInputStream fileInput = openFileInput(message);
InputStreamReader inputStreamReader = new InputStreamReader(fileInput);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer stringBuffer = new StringBuffer();
while ((message = bufferedReader.readLine())!=null){
stringBuffer.append(message+"/n");
}
eventList.setText(stringBuffer.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void noEventToday(){
TextView eventList = (TextView)findViewById(R.id.eventList);
eventList.setText("Nothing scheduled for today.");
}
}
here is my EventCreateActivity:
public class EventCreateActivity extends AppCompatActivity {
String textViewText = CalendarActivity.createEventDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_create);
TextView titleTextView = (TextView)findViewById(R.id.titleTextView);
titleTextView.setText("Create event for "+textViewText);
Button createEventButton = (Button)findViewById(R.id.saveEvent);
createEventButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
buttonSaves();
Intent toCalendarActivity = new Intent(EventCreateActivity.this, CalendarActivity.class);
EventCreateActivity.this.startActivity(toCalendarActivity);
}
});
}
public void buttonSaves () {
TimePicker timePicker = (TimePicker)findViewById(R.id.timePicker);
EditText entryEvent = (EditText)findViewById(R.id.entryEvent);
EditText entryLocation = (EditText)findViewById(R.id.entryLocation);
EditText entryCrew = (EditText)findViewById(R.id.entryCrew);
final String timeHour = timePicker.getCurrentHour().toString();
final String timeMinute = timePicker.getCurrentMinute().toString();;
final String event = entryEvent.getText().toString();
final String location = entryLocation.getText().toString();
final String crew = entryCrew.getText().toString();
try{
FileOutputStream saveNewEvent1 = openFileOutput(textViewText, MODE_WORLD_READABLE);
OutputStreamWriter saveNewEvent2 = new OutputStreamWriter(saveNewEvent1);
try {
saveNewEvent2.write(timeHour);
} catch (IOException e) {
e.printStackTrace();
}
try {
saveNewEvent2.write(timeMinute);
} catch (IOException e) {
e.printStackTrace();
}
try {
saveNewEvent2.write(event);
} catch (IOException e) {
e.printStackTrace();
}
try {
saveNewEvent2.write(location);
} catch (IOException e) {
e.printStackTrace();
}
try {
saveNewEvent2.write(crew);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getBaseContext(), "Roger Roger", Toast.LENGTH_LONG).show();
}catch(FileNotFoundException e){
e.printStackTrace();
}
Log.i("info","The event is: "+timeHour+timeMinute+event+location+crew);
}
}
Related
Hello I tried to make an app for displaying quote in Android Studio.
But I got stuck when reading.
I created an "ArrayList" with my custom class Quotes.
I seems to work ok when writing the ArrayList to the file, but when reading from it the size of ArrayList is 0.
public class SaveQuote extends AppCompatActivity {
EditText editTextQuote;
EditText editTextAuthor;
Button btnSave;
ArrayList<Quote> arrQuo = new ArrayList<>();
public static ArrayList<Quote> arrayListQuotesSave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save_quote);
init();
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String quote = editTextQuote.getText().toString();
String author =editTextAuthor.getText().toString();
addQuote(quote,author);
}
});
}
private void init(){
editTextQuote = findViewById(R.id.editTextQuote);
editTextAuthor = findViewById(R.id.editTextAuthor);
btnSave = findViewById(R.id.buttonSave);
arrayListQuotesSave = new ArrayList<>();
}
private void addQuote(String quote, String author){
Quote q = new Quote(quote, author);
arrQuo.add(q);
String path = this.getFilesDir().toString();
try {
FileOutputStream fos = openFileOutput("Quotes.txt",MODE_APPEND);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(arrQuo);// when I write size = 1
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis = openFileInput("Quotes.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
arrQuo =(ArrayList<Quote>) ois.readObject();
ois.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
I tried to passe a context and call the method openFileOutput on the context
so like this:
enter code here
FileOutputStream fs = context.openFileOutput("Quotes.txt", Context.MODE_PRIVATE);
enter code here
public class SaveQuote extends AppCompatActivity {
EditText editTextQuote;
EditText editTextAuthor;
Button btnSave;
ArrayList<Quote> arrQuo = new ArrayList<>();
public static ArrayList<Quote> arrayListQuotesSave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save_quote);
init();
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String quote = editTextQuote.getText().toString();
String author =editTextAuthor.getText().toString();
if(quote.isEmpty() || author.isEmpty()){
Toast.makeText(SaveQuote.this,"Fill all fields",Toast.LENGTH_SHORT).show();
}else {
writeToFile(SaveQuote.this, quote, author);
Toast.makeText(SaveQuote.this,"The quote was saved",Toast.LENGTH_SHORT).show();
}
}
});
}
private void init(){
editTextQuote = findViewById(R.id.editTextQuote);
editTextAuthor = findViewById(R.id.editTextAuthor);
btnSave = findViewById(R.id.buttonSave);
arrayListQuotesSave = new ArrayList<>();
}
private void writeToFile(Context context,String quote,String author) {
Quote q = new Quote(quote,author);
MainActivity.arrayListQuotesMain.add(q);
Integer size = MainActivity.arrayListQuotesMain.size();
Log.v("Added","arrayListQuotesMain size is = "+size.toString());
try {
FileOutputStream fs = context.openFileOutput("Quotes.txt", Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fs);
oos.writeObject(MainActivity.arrayListQuotesMain);
oos.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
editTextQuote.setText("");
editTextAuthor.setText("");
}
}
I want to play a decoded string to audio file.
The string is received from another activity, but mediaPlayer shows null. How can I get and set the path in media.create()?
public class AAudio extends AppCompatActivity {
Button play_audio;
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aaudio);
String recieve_file = getIntent().getStringExtra("audio_file");
play_audio = findViewById(R.id.textShow);
byte[] decoded = Base64.decode(recieve_file, 0);
String fileName = String.valueOf(decoded);
Log.e("~~~~~~~~ Decoded: ", Arrays.toString(decoded));
try {
String root = Environment.getExternalStorageDirectory().getPath();
File myDir = new File(root, "/kaushlya/mp3");
String path = String.valueOf(myDir);
myDir.mkdirs();
String audioName = "Advicory.mp3";
File file = new File(myDir, audioName);
FileOutputStream os = null;
try {
os = new FileOutputStream(file, true);
os.write(decoded);
os.close();
**mediaPlayer = MediaPlayer.create(this, Uri.parse(Uri.parse(root)+path+fileName));
mediaPlayer.setLooping(true);**
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
catch (Exception e) {
e.printStackTrace();
}
play_audio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.start();
}
});
}
}
I am trying to upload a file from dropbox in another activity from where i autenticate to dropbox. I have this RegisterActivity.java where the user registers and then later when the registration is completed the webbrowser comes up and the user has to allow the dropbox authentication.
later in my app on another activity the user is going to upload a video to dropbox. the upload is made by ASyncTask and works well. The problem is now that i dont want to reauthenticate again. How do i fix that? Is it on the same session or do i start a new session? Now Iam trying to use the sam mDBApi form RegisterAcitivity but i think that is wrong. The keys are stored in the storeKeys() method and saves them in SharedPreferences.
Thank you very much in advance
Here is my RegisterActivity in pastebin which works. http://pastebin.com/K06JUWXv
Here is the activity that where i call my ASyncTask UploadFile:
public class ShowVideo extends Activity{
final static private String ACCOUNT_PREFS_NAME = "prefs";
final static private String ACCESS_KEY_NAME = "ACCESS_KEY";
final static private String ACCESS_SECRET_NAME = "ACCESS_SECRET";
private DropboxAPI<AndroidAuthSession> mDBApi = RegisterActivity.mDBApi;
private String[] storedKeys = getKeys();
UploadFile upload;
public static String path = "";
public static String fileName;
private VideoView ww;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); //Forces landscape orientation which is what the camera uses.
setContentView(R.layout.showvideo);
Button yesButton = (Button) findViewById(R.id.yesButton);
Button noButton = (Button) findViewById(R.id.NoButton);
Button dbButton = (Button) findViewById(R.id.dropboxButton);
dbButton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
if(v.getId() == R.id.dropboxButton){
if (mDBApi.getSession().isLinked() == true){
Log.d("ShowVideo", "TRUE");
}
if (mDBApi.getSession().isLinked() == false){
Log.d("ShowVideo", "FALSE");
}
}
}
});
yesButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(v.getId() == R.id.yesButton){
UploadFile upload = new UploadFile(ShowVideo.this,mDBApi,path);
upload.execute();
}
}
});
noButton.setOnClickListener(new OnClickListener() {
public void onClick(View w) {
File file = new File(path);
boolean deleted = false;
deleted = file.delete();
Log.e("TAG", Boolean.toString(deleted));
Intent intent = new Intent(ShowVideo.this, CaptureVideo.class);
startActivity(intent);
}
});
ww = (VideoView) findViewById(R.id.satisfiedVideoView);
path = getRealPathFromURI(CaptureVideo.uriVideo);
fileName = getFileNameFromUrl(path);
//AndroidAuthSession session = new AndroidAuthSession(new AppKeyPair(ret[0], ret[1]), AccessType.APP_FOLDER);
//mDBApi = new DropboxAPI<AndroidAuthSession>(session);
}
private void playVideo(){
ww.setVideoURI(CaptureVideo.uriVideo);
ww.setMediaController(new MediaController(this));
ww.start();
ww.requestFocus();
}
public static String getFileNameFromUrl(String path) {
String[] pathArray = path.split("/");
return pathArray[pathArray.length - 1];
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
/**DROPBOX-METHOD------------------------------------------*/
private String[] getKeys() {
SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0);
String key = prefs.getString(ACCESS_KEY_NAME, null);
String secret = prefs.getString(ACCESS_SECRET_NAME, null);
if (key != null && secret != null) {
String[] ret = new String[2];
ret[0] = key;
ret[1] = secret;
return ret;
} else {
return null;
}
}
}
Here is my ASyncTask if you would take a look at that. Shouldn't be needed.
public class UploadFile extends AsyncTask<Void, Long, Boolean> {
DropboxAPI<AndroidAuthSession> dDBApi;
Context dContext;
private String SAVE_PATH;
public UploadFile(Context context,DropboxAPI<AndroidAuthSession> mDBApi, String path) {
dContext = context.getApplicationContext();
dDBApi = mDBApi;
SAVE_PATH = path;
}
#Override
protected Boolean doInBackground(Void... params) {
FileInputStream inputStream = null;
try {
File file = new File(SAVE_PATH);
inputStream = new FileInputStream(file);
Entry newEntry = dDBApi.putFileOverwrite("/GAMES/GAME_BETWEEN_USER_A_USER_B/" + "PresentVideo.mp4", inputStream, file.length(), null);
}
catch (DropboxException e) {
Log.e("DbExampleLog", "Something went wrong while uploading.");
} catch (FileNotFoundException e) {
Log.e("DbExampleLog", "File not found.");
} catch (IOException e) {
Log.e("DbExampleLog", "Another Exception:" + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
Log.e("DbExampleLog", "Another Exception:" + e.getMessage());
e.printStackTrace();
}
finally {
if (inputStream != null) {
try {
inputStream.close();
}
catch (IOException e) {
}
}
}
return null;
}
}
I am missing something very crucial but I can't quite see what. Can someone please assist. It's probably something really silly that I have missed but I cannot initiate my onItemClick.
onCreate....
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
actu_ip = intent.getStringExtra(IPEntry.ACTUALSMARTIP);
setContentView(R.layout.act_ipcontrol);
mainListView = (ListView) findViewById( R.id.mainListView );
String[] options = new String[] { "All in to 1", "Spare"};
ArrayList<String> optionsList = new ArrayList<String>();
optionsList.addAll( Arrays.asList(options) );
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, optionsList);
mainListView.setAdapter( listAdapter );
try {
Toast.makeText(IPControl.this, "Please wait...Connecting...", Toast.LENGTH_SHORT).show();
new AsyncAction().execute();
} catch(Exception e) {
e.printStackTrace();
}
}
private class AsyncAction extends AsyncTask<String, Void, String> {
protected String doInBackground(String... args) {
try {
InetAddress serverAddr = InetAddress.getByName(actu_ip);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream());
BufferedWriter bw = new BufferedWriter(osw);
out = new PrintWriter(bw, true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (! in .ready());
readBuffer();
out.println("root\r\n");
while (! in .ready());
readBuffer();
out.println("root\r\n");
while (! in .ready());
readBuffer();
out.println("[verbose,off\r\n");
while (! in .ready());
String msg = "";
while ( in .ready()) {
msg = msg + (char) in .read();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;//returns what you want to pass to the onPostExecute()
}
protected void onPostExecute(String result) {
Toast.makeText(IPControl.this, "Connected", Toast.LENGTH_SHORT).show();
//results the data returned from doInbackground
IPControl.this.data = result;
}
}
private String readBuffer() throws IOException {
String msg = "";
while(in.ready()) {
msg = msg + (char)in.read();
}
//System.out.print(msg);
if(msg.indexOf("SNX_COM> ") != -1) return msg.substring(0, msg.indexOf("SNX_COM> "));
else if(msg.indexOf("SCX_COM> ") != -1) return msg.substring(0, msg.indexOf("SCX_COM> "));
else return msg;
}
}
What I want to initiate...
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
try {
new AsyncAction1().execute();
} catch(Exception e) {
e.printStackTrace();
}
}
private class AsyncAction1 extends AsyncTask<String, Void, String> {
protected String doInBackground(String... args) {
try {
out.println("[c,l#,i1,o*\r\n");
//System.out.print("root\r\n");
while(! in .ready());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;//returns what you want to pass to the onPostExecute()
}
protected void onPostExecute(String result) {
//results the data returned from doInbackground
Toast.makeText(IPControl.this, "Command Sent", Toast.LENGTH_SHORT).show();
IPControl.this.data = result;
}
}
I haven't seen setOnItemClickListener method for listview in your code. Have you implemented it?
Try following
mainListView.setAdapter( listAdapter );
mainListView.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
try {
new AsyncAction1().execute();
}catch(Exception e) {
e.printStackTrace();
}
});
Thanks for all your help, I fixed my problem.
I just wasn't doing things in the correct order.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
actu_ip = intent.getStringExtra(IPEntry.ACTUALSMARTIP);
setContentView(R.layout.act_ipcontrol);
mainListView = (ListView) findViewById( R.id.mainListView );
final String[] options = new String[] { "All in to 1", "Spare"};
ArrayList<String> optionsList = new ArrayList<String>();
optionsList.addAll( Arrays.asList(options) );
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, optionsList);
mainListView.setAdapter( listAdapter );
mainListView.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
try {
if(pos == 0) {
AsyncAction1 a = new AsyncAction1();
a.setCmd("[c,l#,i1,o*\r\n");
a.execute();
}
} catch(Exception e) {
e.printStackTrace();
}
}
});
Then....
private class AsyncAction1 extends AsyncTask<String, Void, String> {
String cmd;
public void setCmd(String c) {
cmd = c;
}
protected String doInBackground(String... args) {
try {
out.println(cmd);
//System.out.print("root\r\n");
while(! in .ready());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;//returns what you want to pass to the onPostExecute()
}
protected void onPostExecute(String result) {
//results the data returned from doInbackground
Toast.makeText(IPControl.this, "Command Sent", Toast.LENGTH_SHORT).show();
IPControl.this.data = result;
}
}
}
Everything works with no errors, but in the xml, tvfinalgrade stays 0.0... Why isn't the double fin being displayed? I'm sure about what order the tvfin code lines should be written, but I'm assuming its not right.
public class GFActivity extends Activity {
public double fin;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.getfinal);
double q1, q2, ex;
EditText etq1, etq2, eteg;
etq1 = (EditText)findViewById(R.id.editText1);
try{
q1 = Double.parseDouble(etq1.getText().toString());
} catch (NumberFormatException e) {
q1=0;
}
etq2 = (EditText)findViewById(R.id.editText2);
try{
q2 = Double.parseDouble(etq2.getText().toString());
} catch (NumberFormatException e){
q2 = 0;
}
eteg = (EditText)findViewById(R.id.editText3);
try{
ex = Double.parseDouble(eteg.getText().toString());
} catch (NumberFormatException e){
ex = 0;
}
fin = 0.4*q1+0.4*q2+0.2*ex;
if(fin == (int)fin){
System.out.println((int)fin);
}
else{
fin = 0.01*((int)(fin*100));
System.out.println(fin);
}
Button solve = (Button)findViewById(R.id.getfinbutton);
solve.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
TextView tvfin= TextView)findViewById(R.id.tvfinalgrade);
tvfin.setText(fin+"");
}
});
}
}
When you start the app, in the onCreate() you already parse the EditText content(which are empty, so you throw NumberFormatException and your fin variable ends up as 0) and when you get to the part of setting the result(the user clicks the Button) you set the fin which is currently 0 to the TextView(the problem is that when the user clicks the Button you never get the current EditText content to do any calculation and the fin variable is the old value(0)). Move your calculation in the onClick() method:
Button solve = (Button)findViewById(R.id.getfinbutton);
solve.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
double q1, q2, ex;
EditText etq1, etq2, eteg;
etq1 = (EditText)findViewById(R.id.editText1);
try{
q1 = Double.parseDouble(etq1.getText().toString());
} catch (NumberFormatException e) {
q1=0;
}
etq2 = (EditText)findViewById(R.id.editText2);
try{
q2 = Double.parseDouble(etq2.getText().toString());
} catch (NumberFormatException e){
q2 = 0;
}
eteg = (EditText)findViewById(R.id.editText3);
try{
ex = Double.parseDouble(eteg.getText().toString());
} catch (NumberFormatException e){
ex = 0;
}
fin = 0.4*q1+0.4*q2+0.2*ex;
if(fin == (int)fin){
System.out.println((int)fin);
}
else{
fin = 0.01*((int)(fin*100));
System.out.println(fin);
}
TextView tvfin= TextView)findViewById(R.id.tvfinalgrade);
tvfin.setText(fin+"");
}
});