Working On A Favorite Websites App - java

Edit: I've made some updates to this ever since I got responses to this thread. Here's the new thread:
I've been making an Android application where you would save your favorite websites. Here is what I got for the code in the file 'MainActivity.java' so far:
package cory.assignment.favoritewebsitesapp;
import java.util.ArrayList;
import java.util.Collections;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends ListActivity {
private static final String SEARCHES = "searches";
private EditText queryEditText;
private EditText tagEditText;
private SharedPreferences savedSearches;
private ArrayList<String> tags;
private ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
queryEditText = (EditText) findViewById(R.id.queryEditText);
tagEditText = (EditText) findViewById(R.id.tagEditText);
savedSearches = getSharedPreferences(SEARCHES, MODE_PRIVATE);
tags = new ArrayList<String>(savedSearches.getAll().keySet());
Collections.sort(tags, String.CASE_INSENSITIVE_ORDER);
adapter = new ArrayAdapter<String>(this, R.layout.list_item, tags);
setListAdapter(adapter);
ImageButton saveButton = (ImageButton) findViewById(R.id.saveButton);
saveButton.setOnClickListener(saveButtonListener);
getListView().setOnItemClickListener(itemClickListener);
getListView().setOnItemLongClickListener(itemLongClickListener);
}
public OnClickListener saveButtonListener = new OnClickListener()
{
#Override
public void onClick(View v)
{
if (queryEditText.getText().length() > 0 && tagEditText.getText().length() > 0)
{
addTaggedSearch(queryEditText.getText().toString(), tagEditText.getText().toString());
queryEditText.setText("");
tagEditText.setText("");
((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(tagEditText.getWindowToken(), 0);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage(R.string.missingMessage);
builder.setPositiveButton(R.string.OK, null);
AlertDialog errorDialog = builder.create();
errorDialog.show();
}
}
};
private void addTaggedSearch(String query, String tag)
{
SharedPreferences.Editor preferencesEditor = savedSearches.edit();
preferencesEditor.putString(tag, query);
preferencesEditor.apply();
if (!tags.contains(tags))
{
tags.add(tag);
Collections.sort(tags, String.CASE_INSENSITIVE_ORDER);
adapter.notifyDataSetChanged();
}
}
OnItemClickListener itemClickListener = new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String tag = ((TextView) view).getText().toString();
String urlString = getString(R.string.searchURL) + Uri.encode(savedSearches.getString(tag, ""), "UTF-8");
Intent webIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(urlString));
startActivity(webIntent);
}
};
OnItemLongClickListener itemLongClickListener =
new OnItemLongClickListener()
{
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
{
final String tag = ((TextView) view).getText().toString();
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(getString(R.string.shareEditDeleteTitle, tag));
builder.setItems(R.array.dialog_items, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
switch (which)
{
case 0:
shareSearch(tag);
break;
case 1:
tagEditText.setText(tag);
queryEditText.setText(savedSearches.getString(tag, ""));
break;
case 2:
deleteSearch(tag);
break;
}
}
}
);
builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
}
);
builder.create().show();
return true;
}
};
private void shareSearch(String tag)
{
String urlString = getString(R.string.searchURL) + Uri.encode(savedSearches.getString(tag, ""), "UTF-8");
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.shareSubject));
shareIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.shareMessage, urlString));
shareIntent.setType("text/plain");
startActivity(Intent.createChooser(shareIntent, getString(R.string.shareSearch)));
}
private void deleteSearch(final String tag)
{
AlertDialog.Builder confirmBuilder = new AlertDialog.Builder(this);
confirmBuilder.setMessage(getString(R.string.confirmMessage, tag));
confirmBuilder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
}
);
confirmBuilder.setPositiveButton(getString(R.string.delete), new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
tags.remove(tag);
SharedPreferences.Editor preferencesEditor = savedSearches.edit();
preferencesEditor.remove(tag);
preferencesEditor.apply();
adapter.notifyDataSetChanged();
}
}
);
confirmBuilder.create().show();
}
}
However, I have got the errors for the code with certain lines:
Line 79: OK cannot be resolved or is not a field
Line 146: cancel cannot be resolved or is not a field
Line 177: cancel cannot be resolved or is not a field
Line 186: delete cannot be resolved or is not a field
The link below shows what I have for activity_main.xml:
Click here for the image
What could be wrong with those lines? Something isn't right with those lines as they are related to the info on this page.
I am also using the proram Eclipse Java EE IDE for Web Developers to make this as well in case you wanted to know what program I was using. I'm also using API 18 to work on this as well.
If you want to take a look at the other files, then let me know.

I know that some of them are strings that I need to make for the strings.xml file, but would their values have to be messages like "This file is missing", or would they have to be special integers?
They need to be in res/values/strings.xml, yes.
Those values are compiled into "special integers" for you and are accessible by R.string.xxxxx.
I imagine that solves the majority of the errors saying "cannot be resolved or is not a field".
DialogInterference cannot be resolved to a type
Did you mean DialogInterface?
The method deleteSearch(string) from the type MainActivity refers to the missing type string
Look at this line. What is string?
private void deleteSearch(final string tag)

So upon examination, I found out that the other lines did need strings after all despite what it said about certain R.string codes on this page for 'cancel' and 'OK'. So why did 'cancel' and 'OK' need their own strings in strings.xml?

Related

Where should I call a method to remove items from a ListView if those items were added through user input from a Popup window?

I have the following code in Android Studio. I'm able to open a popup whenever the "+ New Semester" button is clicked and a new semester is added to the Main Activity once the user types in the semester name in the popup and clicks on the "Done" button. Now, I want to implement a method that removes semesters that are no longer wanted. I made a method called removeSemesters() that I think that does what I want it to do, I haven't been able to test it because I'm not sure where I need to call that method in order to do what I want it to do. Any help would be appreciated! Thank you!
package com.example.gradecalculator;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
// Private Fields
private Dialog d;
private EditText semesterName;
private ListView semesterList;
private ArrayList<String> semesterArray = new ArrayList<String>();
private ArrayAdapter<String> semesterAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
d = new Dialog(this);
}
// When user clicks on "+ New Semester" button open a popup where the user is prompted to
// type in the Semester Name and when "Done" is clicked the new semester appears in the Main
// Activity
public void newSemesterPopup(View v) {
TextView closePopup;
ImageButton doneButton;
d.setContentView(R.layout.new_semester_popup);
semesterName = (EditText) d.findViewById(R.id.editTextSemesterName);
semesterList = (ListView) findViewById(R.id.semesterList);
doneButton = (ImageButton) d.findViewById(R.id.doneButton);
doneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addSemesters();
}
});
closePopup = (TextView) d.findViewById(R.id.exitButton);
closePopup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
}
});
d.show();
}
// Adds semesters to Main Activity
public void addSemesters() {
String getSemesterName = semesterName.getText().toString();
if(semesterArray.contains(getSemesterName)) {
Toast.makeText(getBaseContext(), "Semester Name already exists.", Toast.LENGTH_LONG).show();
}
else if(getSemesterName == null || getSemesterName.trim().equals("")) {
Toast.makeText(getBaseContext(), "Cannot add empty Semester Name", Toast.LENGTH_LONG).show();
}
else {
semesterAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_multiple_choice, semesterArray);
semesterList.setAdapter(semesterAdapter);
semesterAdapter.add(getSemesterName);
d.dismiss();
}
}
// Removes unwanted semesters from Main Activity
public void removeSemesters() {
semesterList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
SparseBooleanArray positionChecker = semesterList.getCheckedItemPositions();
int counter = semesterList.getCount();
for(int i = counter - 1; i > 1; i--) {
if(positionChecker.get(i)) {
semesterAdapter.remove(semesterArray.get(i));
Toast.makeText(MainActivity.this, "Semester deleted successfully.", Toast.LENGTH_LONG).show();
}
}
positionChecker.clear();
semesterAdapter.notifyDataSetChanged();
return false;
}
});
}
// Opens Main Activity
public void openMainActivity() {
Intent main = new Intent(this, MainActivity.class);
startActivity(main);
}
}
I was able to fix this by myself so in case anyone needs the answer in the future I'll leave it here.
I added the following to the onCreate method and it fixed my problem:
semesterName = (EditText) d.findViewById(R.id.editTextSemesterName);
semesterList = (ListView) findViewById(R.id.semesterList);
removeSemesters();
Not a hard fix, I thought of it right after posting the questions. Don't know if this is the most efficient way to do it. If not, feel free to give another answer.

How to save the data a user inputs into the device's local internal storage?

I'm developing a Grade/GPA Calculator app on Android during my free time. What the app basically does until now is let the user add Semesters in the Main Activity and when the user clicks on a certain Semester the user is redirected to another Activity where the user can add new Courses for that specific semester. The problem I'm having is that when the user hits on the back button to go to to the Main Activity where the Semesters are located the courses that were added in that semester are erased. The same happens when I go to the phone's homepage and re-launch the app, everything that the user had created has been deleted.
I'm pretty sure my problem is that I'm not saving the data that the user creates to the phone's storage/app's storage, but I can't seem to figure out on how to do this. If anyone can point me in the right direction I would appreciate it. Thanks!
This is my MainActivity class's code: (My MainActivity is where Semesters are added)
package com.example.gradecalculator;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
// Private Fields
private Dialog d;
private EditText semesterName;
private ListView semesterListView;
private ArrayList<String> semesterArray = new ArrayList<String>();
private SemesterAdapter customSemesterAdapter;
private ArrayList<Semester> mySemesters = new ArrayList<>();
private ArrayList<String> semesterBackgrounds = new ArrayList<String>();
private String getSemesterName;
private int randomBackground[] = new int[7];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initiating toolbar
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Making a new dialog
d = new Dialog(this);
// Initializing variables
semesterName = (EditText) d.findViewById(R.id.editTextSemesterName);
semesterListView = (ListView) findViewById(R.id.semesterList);
// Calling the removeSemesters() method
removeSemesters();
// Adding backgrounds to the backgrounds ArrayList
semesterBackgrounds.add("orange_background");
semesterBackgrounds.add("green_background");
semesterBackgrounds.add("aqua_background");
semesterBackgrounds.add("blue_background");
semesterBackgrounds.add("pink_background");
semesterBackgrounds.add("purple_background");
semesterBackgrounds.add("red_background");
semesterBackgrounds.add("yellow_background");
}
// Creating a custom Menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.top_menu, menu);
return true;
}
// Buttons in the custom Menu
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.editButton:
Toast.makeText(this, "Delete the desired Semesters by clicking on the trash button located to the right of each Semester", Toast.LENGTH_LONG).show();
return true;
}
return super.onOptionsItemSelected(item);
}
// When user clicks on "+New Semester" button open a popup where the user is prompted to
// type in the Semester Name and when "Done" is clicked the new semester appears in the Main
// Activity
public void newSemesterPopup(View v) {
TextView closePopup;
ImageButton doneButton;
d.setContentView(R.layout.new_semester_popup);
semesterName = (EditText) d.findViewById(R.id.editTextSemesterName);
semesterListView = (ListView) findViewById(R.id.semesterList);
doneButton = (ImageButton) d.findViewById(R.id.doneButton);
doneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addSemesters();
}
});
closePopup = (TextView) d.findViewById(R.id.exitButton);
closePopup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
}
});
d.show();
}
// Adds semesters to Main Activity
public void addSemesters() {
getSemesterName = semesterName.getText().toString();
if (semesterArray.contains(getSemesterName)) {
Toast.makeText(getBaseContext(), "Semester Name Already Exists", Toast.LENGTH_SHORT).show();
} else if (getSemesterName == null || getSemesterName.trim().equals("")) {
Toast.makeText(getBaseContext(), "Cannot Add Empty Semester Name", Toast.LENGTH_SHORT).show();
} else {
semesterArray.add(getSemesterName);
mySemesters.add(new Semester(getSemesterName, semesterBackgrounds.get(new Random().nextInt(randomBackground.length))));
customSemesterAdapter = new SemesterAdapter(getApplicationContext(), R.layout.semester_row, mySemesters);
semesterListView.setAdapter(customSemesterAdapter);
d.dismiss();
}
}
// Removes unwanted semesters from Main Activity
public void removeSemesters() {
semesterListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder deleteAlert = new AlertDialog.Builder(MainActivity.this);
deleteAlert.setTitle("Semester Deletion Process");
deleteAlert.setMessage("Are you sure you want to delete the selected Semesters?");
deleteAlert.setNegativeButton("No! Cancel", null);
deleteAlert.setPositiveButton("Yes! Delete", new AlertDialog.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
customSemesterAdapter.remove(customSemesterAdapter.getItem(position));
semesterArray.remove(position);
customSemesterAdapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this, "Semester Deleted Successfully.", Toast.LENGTH_SHORT).show();
}
});
deleteAlert.show();
return false;
}
});
openSemestersActivity();
}
// Open the SemesterActivity and uses .putExtra to pass data to the SemesterActivity to tell it what semester to render
// data accordingly
public void openSemestersActivity() {
final Intent semester = new Intent(this, SemesterActivity.class);
semesterListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
semester.putExtra("semester", semesterName.getText().toString());
startActivity(semester);
}
});
}
}
This is my SemesterActivity code: (My SemestersActivity is where Courses are added)
package com.example.gradecalculator;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import java.util.ArrayList;
import java.util.Random;
public class SemesterActivity extends AppCompatActivity {
// Private Fields
private Dialog d;
private EditText courseName;
private EditText courseCode;
private EditText courseCredits;
private ListView courseListView;
private ArrayList<String> courseArray = new ArrayList<String>();
private CourseAdapter customCourseAdapter;
private ArrayList<Course> myCourses = new ArrayList<>();
private ArrayList<String> coursesBackgrounds = new ArrayList<String>();
private String getCourseName;
private String getCourseCode;
private String getCourseCredits;
private int randomBackground[] = new int[7];
private TextView courseNameView;
private TextView courseCodeView;
private TextView courseCreditsView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_semester);
d = new Dialog(this);
courseNameView = (TextView) d.findViewById(R.id.editTextCourseName);
courseCodeView = (TextView) d.findViewById(R.id.editTextCourseCode);
courseCreditsView = (TextView) d.findViewById(R.id.editTextCourseCredits);
courseListView = (ListView) findViewById(R.id.coursesList);
// Retrieving the Extra and determining the semester we want to load
Intent myIntent = getIntent();
String semester = myIntent.getStringExtra("semester");
removeCourses();
// Initiating toolbar
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Adding backgrounds to the backgrounds ArrayList
coursesBackgrounds.add("orange_background_big");
coursesBackgrounds.add("green_background_big");
coursesBackgrounds.add("aqua_background_big");
coursesBackgrounds.add("blue_background_big");
coursesBackgrounds.add("pink_background_big");
coursesBackgrounds.add("purple_background_big");
coursesBackgrounds.add("red_background_big");
coursesBackgrounds.add("yellow_background_big");
}
// Creating a custom Menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.top_menu, menu);
return true;
}
// Buttons in the custom Menu
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.editButton:
Toast.makeText(this, "Delete the desired Courses by clicking on the trash button located to the right of each Semester", Toast.LENGTH_LONG).show();
return true;
}
return super.onOptionsItemSelected(item);
}
// New course popup
public void newCoursePopup(View v) {
TextView closePopup;
ImageButton doneButton;
d.setContentView(R.layout.new_course_popup);
courseName = (EditText) d.findViewById(R.id.editTextCourseName);
courseCode = (EditText) d.findViewById(R.id.editTextCourseCode);
courseCredits = (EditText) d.findViewById(R.id.editTextCourseCredits);
doneButton = (ImageButton) d.findViewById(R.id.doneButton);
doneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addCourses();
}
});
closePopup = (TextView) d.findViewById(R.id.exitButton);
closePopup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
}
});
d.show();
}
// Adding courses to the Semester
public void addCourses() {
getCourseName = courseName.getText().toString();
getCourseCode = courseCode.getText().toString();
getCourseCredits = courseCredits.getText().toString();
if(courseArray.contains(getCourseName)) {
Toast.makeText(getBaseContext(), "Course Name Already Exists", Toast.LENGTH_SHORT).show();
}
else if(getCourseName == null || getCourseName.trim().equals("")) {
Toast.makeText(getBaseContext(), "Cannot Add Empty Course Name", Toast.LENGTH_SHORT).show();
}
else {
courseArray.add(getCourseName);
myCourses.add(new Course(getCourseName, getCourseCode, getCourseCredits, coursesBackgrounds.get(new Random().nextInt(randomBackground.length))));
customCourseAdapter = new CourseAdapter(getApplicationContext(), R.layout.course_row, myCourses);
courseListView.setAdapter(customCourseAdapter);
d.dismiss();
}
}
// Removing courses from the Semester
public void removeCourses() {
courseListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder deleteAlert = new AlertDialog.Builder(SemesterActivity.this);
deleteAlert.setTitle("Course Deletion Process");
deleteAlert.setMessage("Are you sure you want to delete the selected Courses?");
deleteAlert.setNegativeButton("No! Cancel", null);
deleteAlert.setPositiveButton("Yes! Delete", new AlertDialog.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
customCourseAdapter.remove(customCourseAdapter.getItem(position));
courseArray.remove(position);
customCourseAdapter.notifyDataSetInvalidated();
Toast.makeText(SemesterActivity.this, "Course Deleted Successfully", Toast.LENGTH_SHORT).show();
}
});
deleteAlert.show();
return false;
}
});
}
}
There are a couple of databases you can look into; You can use Room or Realm. You can also check out online DBs like Firestore by Firebase. The beauty about having an online db a user(Student) can access their data from a different phone if they lose or replace their current one. A recommended way to go is to have both to cover both scenarios.

How to open a new activity from a dialog fragment

My program opens a DialogFragment class while running in MainActivity.java
I want to be able to click on the "neutral button" of that dialog and open a new activity, SensorDataDisplay.java
I am having trouble finding the right way to reference the Context in my button's onClick.
package com.august.customtisensortagclient;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import java.util.ArrayList;
public class GetInfoDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final String thisWhichGetInfoDialog = ((MainActivity)getActivity()).getWhichGetInfoDialog();
final ArrayList<String> thisScannedDevicesArrayList =
((MainActivity)getActivity()).getScannedDevicesArrayList();
final int thisIsInLeftConnectedDeviceDisplay = ((MainActivity)getActivity()).getIsInLeftConnectedDeviceDisplay();
final int thisIsInRightConnectedDeviceDisplay = ((MainActivity)getActivity()).getIsInRightConnectedDeviceDisplay();
int thisIsInThisConnectedDeviceDisplay = 0;
if (thisWhichGetInfoDialog == "Left") {
thisIsInThisConnectedDeviceDisplay = thisIsInLeftConnectedDeviceDisplay;
} else if (thisWhichGetInfoDialog == "Right")
thisIsInThisConnectedDeviceDisplay = thisIsInRightConnectedDeviceDisplay;
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(thisWhichGetInfoDialog + " Sensor Info");
builder.setMessage("MAC Address: " + thisScannedDevicesArrayList.get(thisIsInThisConnectedDeviceDisplay));
builder.setNeutralButton("View Data", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent myIntent = new Intent(?????, SensorDataDisplay.class);
myIntent.putExtra("key", "TEST VALUE"); //Optional parameters
?????.startActivity(myIntent);
}
});
builder.setNegativeButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
return builder.create();
}
}
DialogFragment has getActivity() and getContext() methods (which it inherits from Fragment), both will work in your case. If you're having trouble accessing these methods from the anonymous class (which shouldn't be the case), you can use the GetInfoDialog.this.getActivity() syntax.
getActivity() returns the Activity the fragment is attached to
builder.setNeutralButton("View Data", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent myIntent = new Intent(getActivity(), SensorDataDisplay.class);
myIntent.putExtra("key", "TEST VALUE"); //Optional parameters
getActivity().startActivity(myIntent);
}
});

Save State of a radio button in dialog when ok is pressed and dialog is dismissed

Currently, I have a popup dialogue that shows when I press the currency button, this dialogue contains a set of radio buttons that users can select one of them. I'm trying to get the selected radio button's state to be saved when the user pressed "OK". So that when they press the "Currency" button again, the radio button selection was the one the user chose prior to pressing "OK".
Currently, my code is this:
CurrencyChoiceDialog.java
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.widget.Toast;
public class CurrencyChoiceDialog extends DialogFragment {
final CharSequence[] currencies = {"CAD", "USD", "EURO", "POUNDS"};
String selectedCurrency;
public int selectedElement = -1;
#Override
#NonNull
public Dialog onCreateDialog(Bundle savedInstance){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose the default currency").setSingleChoiceItems(currencies, selectedElement, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
switch (i){
case 0:
selectedCurrency = (String)currencies[i];
selectedElement = i;
break;
case 1:
selectedCurrency = (String)currencies[i];
selectedElement = i;
break;
case 2:
selectedCurrency = (String)currencies[i];
selectedElement = i;
break;
case 3:
selectedCurrency = (String)currencies[i];
selectedElement = i;
break;
default:
break;
}
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getActivity(), "The chosen currency is: "+ selectedCurrency, Toast.LENGTH_LONG);
}
});
return builder.create();
}
}
Settings.java
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class Settings extends AppCompatActivity implements View.OnClickListener {
Button confirm;
Switch useDefault;
boolean toggle;
private CardView currency;
private CardView tipPercentage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
confirm = findViewById(R.id.saveButton);
useDefault = findViewById(R.id.switch1);
currency = findViewById(R.id.currencyButton);
tipPercentage = findViewById(R.id.tipPercentageButton);
confirm.setOnClickListener(this);
currency.setOnClickListener(this);
tipPercentage.setOnClickListener(this);
final SharedPreferences sharedPreferences = getSharedPreferences("Press", 0);
toggle = sharedPreferences.getBoolean("Switch", false);
useDefault.setChecked(toggle);
useDefault.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
toggle = !toggle;
useDefault.setChecked(toggle);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("Switch", toggle);
editor.apply();
}
});
}
#Override
public void onClick(View view) {
Intent i;
switch (view.getId()) {
case R.id.saveButton:
i = new Intent(this, MainActivity.class);
startActivity(i);
break;
// TODO: Save the state once the OK button is clicked for the currency.
case R.id.currencyButton:
setCurrency(view);
break;
// TODO: Finish implementing the changes in the seekbar and reflecting it with the percentage text, and saving that state in the application
case R.id.tipPercentageButton:
showDialog();
break;
default:
break;
}
}
public void setCurrency(View view) {
CurrencyChoiceDialog currencyChoiceDialog = new CurrencyChoiceDialog();
currencyChoiceDialog.show(getSupportFragmentManager(), "CurrencySelection");
}
public void showDialog() {
final Dialog yourDialog = new Dialog(this);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.dialog_tippercentage, (ViewGroup) findViewById(R.id.your_dialog_root_element));
Button yourDialogButton = (Button) layout.findViewById(R.id.your_dialog_button);
SeekBar yourDialogSeekBar = (SeekBar) layout.findViewById(R.id.your_dialog_seekbar);
yourDialog.setContentView(layout);
yourDialog.show();
yourDialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
yourDialog.dismiss();
}
});
}
}
I've tried numerous solutions here but none worked. So any help would be much appreciated. This is my first time trying to make a setting's page for an application. So please make sure your answers are thorough as possible. Thanks in advance.
As I understood the problem, you have to change the variable type of selectedElement from public int to public static int. Furthermore, a quick look to your first listing shows that all switch (i) cases in the function onCreateDialog are applying the same logic, so they are redundant and you can have the same logic by just one case.
Two way to fix this:
Using SharedPreferences: set/get your selectedElement using SharedPreferences
(It will store for long time, after exit from the app also)
OR
Make selectedElement as public static in your in CurrencyChoiceDialog like:
(It will store only when you are on the screen)
public static int selectedElement = -1;
Removed the switch cases and simplified it into one case. As well as had the selectedElement to be static. so it becomes:
public class CurrencyChoiceDialog extends DialogFragment {
final CharSequence[] currencies = {"CAD", "USD", "EURO", "POUNDS"};
String selectedCurrency;
public int selectedElement = -1;
#Override
#NonNull
public Dialog onCreateDialog(Bundle savedInstance){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose the default currency").setSingleChoiceItems(currencies, selectedElement, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
selectedCurrency = (String)currencies[i];
selectedElement = i;
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getActivity(), "The chosen currency is: "+ selectedCurrency, Toast.LENGTH_LONG);
}
});
return builder.create();
}
}
The -1 in (int cheched) here is the default selected item index (-1 means do not select any default). use this parameter to set the default selected.
AlertDialog.Builder builder=new AlertDialog.Builder(this);
String[] items={"item1","item2"};
SharedPreferences prefs=getPreferences(MODE_PRIVATE);
// If you open the dialog again, we'll put the previously saved option here..
int checked = prefs.getInt("checked", -1);
builder.setTitle("your Title")
.setCancelable(false)
.setSingleChoiceItems(languages, checked , (dialog, which) -{
if (which==0) {
// if selected first item ~ code..
}else if (which==1){
// if selected second item ~ code..
}
// then put your selected item in Shared Preferences to save it..
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("checked",which);
editor.apply();
})
.setNegativeButton(Cancel,null)
.setPositiveButton(OK, (dialog, which) -> {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}

RecycleView Wont update

I'm still new with both Java and android
My problem is that the recycleview only gets updated and adds the new added tag if I closed the app and run it again. How can I get the app to update the recycle view instantly to display the new tags.
java code
package com.deitel.favoritesites;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.DialogPreference;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TextInputLayout;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Adapter;
import android.widget.EditText;
import android.widget.TextView;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String SITES="Sites";
private EditText urlEditText; //where user enters the URL
private EditText tagEditText;
private FloatingActionButton saveFloatingActionButton;
private SharedPreferences savedSites;
private List<String> tags;
private SitesAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
urlEditText = ((TextInputLayout) findViewById(
R.id.URLTextInputLayout)).getEditText();
urlEditText.addTextChangedListener(textWatcher);
tagEditText=((TextInputLayout)findViewById(R.id.tagTextInputLayout)).getEditText();
tagEditText.addTextChangedListener(textWatcher);
//get the shared prefrences containing the user saved URLs
savedSites = getSharedPreferences(SITES, MODE_PRIVATE);
//get the shared tags in an ArrayList then sort them
tags = new ArrayList<>(savedSites.getAll().keySet());
Collections.sort(tags, String.CASE_INSENSITIVE_ORDER);
//get reference to the recycle to configure it
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
//use a linerlayout to display items in a vertical list
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//create recyclerView.Adopter to bind tags to the RecyclerView
adapter = new SitesAdapter(tags, itemClickListener, itemLongClickListener);
recyclerView.setAdapter(adapter);
recyclerView.addItemDecoration(new ItemDivider(this));
//register listner to save a new or edit search
saveFloatingActionButton = (FloatingActionButton) findViewById(R.id.fab);
saveFloatingActionButton.setOnClickListener(saveButtonListener);
updateSaveFAB();
}
private final TextWatcher textWatcher= new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
updateSaveFAB();
}
#Override
public void afterTextChanged(Editable s) {
}
};
//show or hide the saveFloatingActionButton
private void updateSaveFAB() {
//check if there is input in both EditButton
if (urlEditText.getText().toString().isEmpty() || tagEditText.getText().toString().isEmpty())
saveFloatingActionButton.hide();
else
saveFloatingActionButton.show();
}
//saveButtonListener save a tag query pair into sharedPrefrece
private final OnClickListener saveButtonListener=new OnClickListener() {
#Override
public void onClick(View view) {
String query = urlEditText.getText().toString();
String tag = tagEditText.getText().toString();
if (!query.isEmpty() && !tag.isEmpty()) {
//hide the virtual keyboard
((InputMethodManager) getSystemService(
Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(view.getWindowToken(),0);
addTaggedSites(tag, query);//add/update the search
urlEditText.setText("");//Clear queryEditText
tagEditText.setText("");//clear tagEditText
urlEditText.requestFocus();
}
}
};
//add new search to file then refresh all button
private void addTaggedSites(String tag, String query) {
//get a sharedprefrence editor to store new tag/query pair
SharedPreferences.Editor preferencesEditor = savedSites.edit();
preferencesEditor.putString(tag, query);
preferencesEditor.apply();
//if tag is new> add and sort tags then display update
if (!tag.contains(tag)) {
tags.add(tag);
Collections.sort(tags, String.CASE_INSENSITIVE_ORDER);
adapter.notifyDataSetChanged();
}
}
//itemClickListener launches web broswer to display search results
private final OnClickListener itemClickListener=new OnClickListener() {
#Override
public void onClick(View view) {
//get query string and create a URL represeting the search
String tag= ((TextView) view).getText().toString();
String urlString=getString(R.string.search_URL)+Uri.encode(savedSites.getString(tag,""),"UTF-8");
//create an intent to lanuch a web broswer
Intent webIntent= new Intent(Intent.ACTION_VIEW,Uri.parse(urlString));
startActivity(webIntent);
}
};
//itemLongClickListener displays a dialog allowing the user to share edit or delete a saved search
private final OnLongClickListener itemLongClickListener= new OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
//get the tag that the user long touched
final String tag = ((TextView) view).getText().toString();
//creatw a new AlertDialog
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
//set the alertDialog title
builder.setTitle(getString(R.string.share_edit_delete_title, tag));
//set list of items to display and create event handler
builder.setItems(R.array.dialog_items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0://share
shareSites(tag);
break;
case 1://edit
tagEditText.setText(tag);
urlEditText.setText(savedSites.getString(tag, ""));
break;
case 2: //delete
deleteSites(tag);
break;
}
}
}
);
//set the alertDialog negetive button
builder.setNegativeButton(getString(R.string.cancel), null);
builder.create().show();//display the alert dialog
return true;
}
};
//allow user to choose app for sharing URL of a saved search
private void shareSites(String tag){
//create the URL representing the search
String urlString= getString(R.string.search_URL)+Uri.encode(savedSites.getString(tag, ""), "UTF-8");
//create an intent to share urlString
Intent shareIntent= new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.share_subject));
shareIntent.putExtra(Intent.EXTRA_TEXT,getString(R.string.share_message,urlString));
shareIntent.setType("text/plain");
//display app that can share plain text
startActivity(Intent.createChooser(shareIntent,getString(R.string.share_search)));
}
//delete search after user confirms
private void deleteSites(final String tag){
//create a new AlertDialog and set its message
AlertDialog.Builder confirmBuilder= new AlertDialog.Builder(this);
confirmBuilder.setMessage(getString(R.string.confirm_message, tag));
//cancel button configration
confirmBuilder.setNegativeButton(getString(R.string.cancel), null);
//positive DELETE button
confirmBuilder.setPositiveButton(getString(R.string.delete),new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog , int id){
tags.remove(tag);
//remove sharedPerefrences.Editor from Sharedprefrences
SharedPreferences.Editor preferenceEditor= savedSites.edit();
preferenceEditor.remove(tag);
preferenceEditor.apply();
adapter.notifyDataSetChanged();
}
}
);
confirmBuilder.create().show();
}
}
This is my adopter code
package com.deitel.favoritesites;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class SitesAdapter extends RecyclerView.Adapter<SitesAdapter.ViewHolder> {
private final View.OnClickListener clickListener;
private final View.OnLongClickListener longClickListener;
private final List<String> tags;
public SitesAdapter(List<String> tags, View.OnClickListener clickListener, View.OnLongClickListener longClickListener) {
this.tags = tags;
this.clickListener = clickListener;
this.longClickListener = longClickListener;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public final TextView textView;
public ViewHolder(View itemView, View.OnClickListener clickListener, View.OnLongClickListener longClickListener) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.textView);
itemView.setOnClickListener(clickListener);
itemView.setOnLongClickListener(longClickListener);
}
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return (new ViewHolder(view, clickListener, longClickListener));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.textView.setText(tags.get(position));
}
#Override
public int getItemCount() {
return tags.size();
}
}
Change your code into this
if (!tags.contains(tag)) {
tags.add(tag);
Collections.sort(tags, String.CASE_INSENSITIVE_ORDER);
adapter.notifyDataSetChanged();
}
Because, this below condition is always false
if(!tag.contains(tag))
Its because you are checking if a value contains in that value itself. SO it will be always true.
If you are checking the tag exist in the List<String> tags you should do like this below.
if(!tags.contains(tag))
change your code to....
//add new search to file then refresh all button
private void addTaggedSites(String tag, String query) {
//get a sharedprefrence editor to store new tag/query pair
SharedPreferences.Editor preferencesEditor = savedSites.edit();
preferencesEditor.putString(tag, query);
preferencesEditor.apply();
//if tag is new> add and sort tags then display update
if (!this.tag.contains(tag)) {
this.tags.add(tag);
Collections.sort(tags, String.CASE_INSENSITIVE_ORDER);
adapter.notifyDataSetChanged();
}
}
This may help:
create a setter method within your adapter allowing you to set/update the adapter ArrayList.
Whenever you make a change to your list i.e. remove Tag, pass this updated list to your adapter via your new setter method.
call notifyDataSetChanged().

Categories