Changing the text of a TextView inside a ListView - java

I'm making a simple to do list and I want to be able to click on the item and enter a new text which will then replace the text of the TextView in that cell. I've got the dialogAlert working, I just don't know how to grab the cell's TextView and change it
This is what the Activity looks like,
public class MainActivity extends AppCompatActivity {
private ListDataSource ds;
private ListView listViewToDo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Context context = this;
Log.d("MainActivity","Attempting to create data source");
try {
ds = new ListDataSource();
}
catch(Exception e)
{
e.printStackTrace();
Log.d("MainActivity","Failed to create data source");
}
Log.d("Main Activity","Attempting to link empty list view to on screen view");
listViewToDo = (ListView)findViewById(R.id.listOfLists);
Log.d("Main Activity","Views linked, Attempting to set adapter to listView");
listViewToDo.setAdapter(new ListDataSourceAdapter(this, ds));
Log.d("Main Activity", "Successfully set Adapter");
// add button listener
listViewToDo.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id)
{
AlertDialog.Builder editItem = new AlertDialog.Builder(context);
final EditText edittext = new EditText(context);
editItem.setTitle("Change Item");
editItem
.setMessage("Set new todo item")
.setView(edittext)
.setCancelable(false)
.setPositiveButton("Submit", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
//what do I put here?
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
});
AlertDialog alertDialog = editItem.create();
alertDialog.show();
}
});
}
}

ds.remove(position);
ds.add(position,edittext.getText().toString().trim())
ListDataSourceAdapter adapter = new ListDataSourceAdapter(this, ds)
listViewToDo.setAdapter(adapter );
adapter.notifDataSetChanged();

Related

Save items added to scroll view android studios

I have created and been able to label items that have been added to a scroll view. I want to find a way to save and store the items created so that when the user clicks off the page they still remain there.
I wanted to do this through the use of sharedprefs however I am not sure how and where the best place would be to add code. Would appreciate any suggestions.
public class Editscreen extends AppCompatActivity {
// https://codevedanam.blogspot.com/2021/04/dynamic-views-in-android.html
Button add;
AlertDialog dialog;
LinearLayout layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_editscreen);
add = findViewById(R.id.button7);
layout = findViewById(R.id.container);
buildDialog();
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
}
private void buildDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
View view = getLayoutInflater().inflate(R.layout.dialog,null);
EditText name = view.findViewById(R.id.nameEdit);
name.getText().clear();
builder.setView(view);
builder.setTitle("Enter Quiz name");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
addCard(name.getText().toString());
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog = builder.create();
}
private void addCard(String name) {
View view = getLayoutInflater().inflate(R.layout.cardlayout,null);
TextView nameView = view.findViewById(R.id.name);
Button delete = view.findViewById(R.id.deletequiz);
nameView.setText(name);
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
layout.removeView(view);
}
});
layout.addView(view);
}
I believe you can add this file to your project and you can call this static functions to save your data to pref. This is the compact way.
public class PrefUtil {
private static SharedPreferences getPrefs(Context context) {
return context.getSharedPreferences(context.getPackageName() + "_preferences",Context.MODE_PRIVATE);
}
public static void setStringPref(Context context,String key,String deger){
getPrefs(context).edit().putString(key,deger).apply();
}
public static String getStringPref(Context context,String key){
return getPrefs(context).getString(key,"");
}
public static void setIntPref(Context context,String key,int deger){
getPrefs(context).edit().putInt(key,deger).apply();
}
public static int getIntPref(Context context,String key){
return getPrefs(context).getInt(key, -1);
}
}

Custom Dialog error 'android.text.Editable android.widget.EditText.getText()' on a null object reference

I have created a custom dialog showing a grid of items. When another option is clicked, it will also open another custom dialog with an editText field. The problem I am facing is getting a null object error for the textfield. I found an answer here but when I applied it, the result is still the same.
Basically, the app is crashing when retrieving the textfield value in the custom dialog that opens from another custom dialog. Here is what I have so far:
onCreate()
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button donate = findViewById(R.id.button);
donate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDonateDialog();
}
});
}
showDonateDialog()
//Donate dialog with grid options
private void showDonateDialog() {
// Prepare grid view
GridView gridView = new GridView(this);
String[] donateAmount = getResources().getStringArray(R.array.donationAmount);
List<String> donateList = new ArrayList<String>();
Collections.addAll(donateList, donateAmount);
gridView.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, donateList));
gridView.setNumColumns(3);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Thank you for your donation!", Toast.LENGTH_SHORT).show();
}
});
// Set grid view to alertDialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(gridView);
builder.setTitle("Donate");
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setNeutralButton("Other amount", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
showCustomDonate();
}
});
builder.setCancelable(false);
builder.show();
}
showCustomDonate()
//Donate dialog for custom amount
private void showCustomDonate() {
AlertDialog.Builder builderCustom = new AlertDialog.Builder(this);
Context context = builderCustom.getContext();
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.custom_donate_amount, null, false);
final EditText donateAmount = findViewById(R.id.editAmount);
final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_NEGATIVE) {
dialog.cancel();
} else {
String amount = donateAmount.getText().toString(); //Error null object reference here
Toast.makeText(getApplicationContext(), "Thank you for donating " + amount, Toast.LENGTH_LONG).show();
}
}
};
builderCustom.setView(view)
.setTitle("Custom Donation")
.setCancelable(false)
.setPositiveButton("OK", listener)
.setNegativeButton("CANCEL", listener)
.show();
}
Log
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.customdialog, PID: 12011
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.example.customdialog.MainActivity$5.onClick(MainActivity.java:94)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
i hope it is work for you
showCustomDonate()
//Donate dialog for custom amount
private void showCustomDonate() {
AlertDialog.Builder builderCustom = new AlertDialog.Builder(this);
Context context = builderCustom.getContext();
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.custom_donate_amount, null, false);
final EditText donateAmount = findViewById(R.id.editAmount);
final DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_NEGATIVE) {
dialog.cancel();
} else {
String amount = donateAmount.getText().toString(); //Error null object reference here
Toast.makeText(getApplicationContext(), "Thank you for donating " + amount, Toast.LENGTH_LONG).show();
}
}
};
builderCustom.setView(view)
.setTitle("Custom Donation")
.setCancelable(false)
.setPositiveButton("OK", listener)
.setNegativeButton("CANCEL", listener)
.show();
}
Change on this line
final EditText donateAmount = view.findViewById(R.id.editAmount);

How to Save Value of ListView In Android

I was recently working on a todo list application in android studio where the user will input text through an EditText, and then the String will be added to a listView as shown below.
public class MainActivity extends AppCompatActivity {
private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
private ListView lvItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvItems = (ListView) findViewById(R.id.lvItems);
items = new ArrayList<>();
itemsAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, items);
lvItems.setAdapter(itemsAdapter);
}
private void setupListViewListener() {
lvItems.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter,
View item, int pos, long id) {
// Remove the item within array at position
items.remove(pos);
// Refresh the adapter
itemsAdapter.notifyDataSetChanged();
return true;
}
});
}
public void addTask(View v) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.dialog, null);
dialogBuilder.setView(dialogView);
final EditText edt = (EditText) dialogView.findViewById(R.id.edit1);
dialogBuilder.setTitle("Add a New Task");
dialogBuilder.setMessage("Enter what you want to do");
dialogBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String itemText = edt.getText().toString();
itemsAdapter.add(itemText);
edt.setText("");
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
AlertDialog b = dialogBuilder.create();
b.show();
}
}
But the problem I have is that when the user closes the activity, the state of the ListView will change back to it's original value.
I want the ListView to retain the Information that has been put inside it when the activity closes.
How do I go about this?
There are many ways to save data in your app.
You can use the following options:
SharedPreferences
Files
SQLite (with plain sql or with the framework Room)
For more information check this link : https://developer.android.com/training/data-storage/index.html
Usually for this situation using Sqlite
But you can use others way such as Shared preference or File
Like you can see here: https://developer.android.com/guide/topics/data/data-storage.html

Item not deleting from sharedpreferences

I have a list that I saved in sharedpreferences I want to delete an item from the listview when the user longclicks so on the long click the app prompts you with a question to delete or not when you confirm it deletes it. This works but when i come back to the activity the list still contains that item that has been deleted
This is the code for the onCreateView. tinyDB is sharedprefrences.Thank you
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tab_secondsemester, container, false);
btnAddNew = (Button)rootView.findViewById(R.id.btnAddNewYearOneSecondSemester);
listView = (ListView)rootView.findViewById(R.id.listViewSubjectsMyCoursesSecondSemester);
tinyDB = new TinyDB(getContext());
storedList = new ArrayList<>(tinyDB.getListString("storedList"));
generalList = new ArrayList<>();
spinnerValues = new ArrayList<>();
getActivity().setTitle("Year One");
setHasOptionsMenu(true);
btnAddNew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext(),R.style.DialogeTheme);
// Setting Dialog Title
alertDialog.setTitle("Add new");
// Setting Dialog Message
String getUsername = tinyDB.getString("Username");
alertDialog.setMessage("Hello "+ getUsername + ", please write the new subject");
final EditText input = new EditText(getContext());
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
input.setTextColor(Color.parseColor("#f06292"));
alertDialog.setView(input);
alertDialog.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String getSubjectInput = input.getText().toString();
storedList.add(getSubjectInput);
tinyDB.putListString("storedList", storedList);
arrayAdapter.notifyDataSetChanged();
}
});
alertDialog.setNegativeButton("CANCEL",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.create();
alertDialog.show();
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(final AdapterView<?> adapterView, View view, final int i, long l) {
new SweetAlertDialog(getContext(), SweetAlertDialog.WARNING_TYPE)
.setTitleText("Delete")
.setContentText("Are you sure you want to delete this course")
.setConfirmText("YES")
.setCancelText("NO")
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
storedList.remove(i);
arrayAdapter.notifyDataSetChanged();
tinyDB.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
arrayAdapter.notifyDataSetChanged();
}
});
sweetAlertDialog.dismiss();
}
})
.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
sweetAlertDialog.dismiss();
}
})
.show();
return true;
}
});
arrayAdapter = new CustomListAdapter(getContext(),storedList);
listView.setAdapter(arrayAdapter);
arrayAdapter.notifyDataSetChanged();
return rootView;
}
Use this when the user deletes it
public void removeAt(int position) {
mDataset.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, mDataSet.size());
}
mDataset is the array/list in which you save all the data for the adapter

NullPointerException trying to get PositiveButton of DialogFragment

In my Android application I created a custom DialogFragment with a custom View but I want the Positive and Negative Button with transparent background.
So I saw some SO answers and i did something like this:
private class PersonalInfoDialogFragment extends DialogFragment {
#Override
public void onStart(){
super.onStart();
Button pButton = ((AlertDialog) getDialog()).getButton(DialogInterface.BUTTON_POSITIVE);
Button nButton = ((AlertDialog) getDialog()).getButton(DialogInterface.BUTTON_NEGATIVE);
pButton.setBackgroundColor(getResources().getColor(Color.TRANSPARENT));
nButton.setBackgroundColor(getResources().getColor(Color.TRANSPARENT));
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
final View view=inflater.inflate(R.layout.personalinformation_dialog, null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.personalinformation)
.setView(view)
.setPositiveButton(R.string.edit, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//Some code
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
final AlertDialog dialog = builder.create();
//I also tried this: dialog.getButton(DialogInterface.BUTTON_POSITIVE).setBackgroundColor(Color.TRANSPARENT);
return dialog;
}
}
I don't get why I am facing NullPointerException. Any idea?
public Button pButton ,nButton ;
#Override
public void onStart(){
super.onStart();
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
final View view=inflater.inflate(R.layout.personalinformation_dialog, null);
pButton = ((AlertDialog) getDialog()).getButton(DialogInterface.BUTTON_POSITIVE);
nButton = ((AlertDialog) getDialog()).getButton(DialogInterface.BUTTON_NEGATIVE);
pButton.setBackgroundColor(getResources().getColor(Color.TRANSPARENT));
nButton.setBackgroundColor(getResources().getColor(Color.TRANSPARENT));
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.personalinformation)
.setView(view)
.setPositiveButton(R.string.edit, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//Some code
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
// Create the AlertDialog object and return it
final AlertDialog dialog = builder.create();
//I also tried this: dialog.getButton(DialogInterface.BUTTON_POSITIVE).setBackgroundColor(Color.TRANSPARENT);
return dialog;
}
}

Categories

Resources