I am new to Android and Java but I have been trying to do this for a while now and have some ideas to how this may work, but I don't know how to put it in code.
I have two Activities, one that is a Log and one that creates a new log. Basically, when a user makes a new log and saves it, it is saved as a keyset with the key being the Log Name.
I then want to take the newly created Log entry and add it to my list on another Activity.
I can only seem to populate the first item in the list with all the KeySets instead of them being listed one by one by adding as a new item.
The code I need is just to populate each item in the ListView as one of the Keys in the KeySets and when the user clicks it loads the values.
The code I have from ActivityLog:
public void loadLog (View view){
SharedPreferences userInfo = getSharedPreferences("userData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = userInfo.edit();
String myString = userInfo.getAll().keySet().toString();
String[] values = new String[] { myString
};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.activity_list_item, android.R.id.text1 );
Map<String, ?> allEntries = userInfo.getAll();
for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
Log.d("map values", entry.getKey() + ": " + entry.getValue().toString());
listView.setAdapter(adapter);
}}
Code for ActivityNewLog:
public void saveLog (View view){
EditText Date = (EditText)findViewById(R.id.editDate);
EditText Name = (EditText)findViewById(R.id.editName);
EditText Cal = (EditText)findViewById(R.id.editCal);
EditText STime = (EditText)findViewById(R.id.editSTime);
EditText ETime = (EditText)findViewById(R.id.editETime);
EditText Entry = (EditText)findViewById(R.id.editEntry);
try {
SharedPreferences userInfo = getSharedPreferences("userData", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = userInfo.edit();
Set<String> LogSet = new HashSet<String>();
LogSet.add(Date.getText().toString());
LogSet.add(Name.getText().toString());
LogSet.add(Cal.getText().toString());
LogSet.add(STime.getText().toString());
LogSet.add(ETime.getText().toString());
editor.putStringSet( Entry.getText().toString(), LogSet);
editor.commit();
Context context = getApplicationContext();
CharSequence text = "User data saved!";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
catch(Exception ex) {
// insert your own error message here
}
}
I would appreciate any help or advice to improve this code.
I would recommend you use a SQLite database instead, but here you put a key into the SharedPreferences / HashMap.
editor.putStringSet( Entry.getText().toString(), LogSet);
Now, you have to get that value back out...
Map<String, ?> allEntries = userInfo.getAll();
Set<String> entry = allEntries.get("<some value here>"); // <-- Whatever you put in
And when you have that, you can loop over them to add to the adapter.
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.activity_list_item, android.R.id.text1 );
listView.setAdapter(adapter);
for (String s : entry) {
adapter.add(s);
}
Related
Scenario:
I have four edittexts and three buttons, where, when the user provides some input in one of the edittexts and either clicks on button 1 or button 2, the provided input by the user should be saved in the activity associated with the button 3. In general, button 3 activity stores the "history" of provided inputs by the user.
Currently, I am using sharedpreferences approach which I know that it is not a good approach if you want to store multiple values. I have tried solving this problem using SQLite database and I was not successful with it.
Here is my method called "saveHistory" which is defined in the button 1's and button 2' onclick methods.
private void saveHistory()
{
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
fd=sharedPreferences.edit();
String et1 = et1.getText().toString();
String et2 = et2.getText().toString();
String et3 = et3.getText().toString();
String et4 = et4.getText().toString();
fd.putString("et1" , et1);
fd.putString("et2" , et2);
fd.putString("et3" , et3);
fd.putString("et4" , et4);
fd.apply();
}
And here is my another class (when clicking on button 3 this class gets called) which retrieves the edittexts values.
public class history extends Activity
{
public static final String DEFAULT = "No data";
ListView listView;
SharedPreferences sharedPreferences;
SharedPreferences.Editor sp;
public ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
listView = (ListView) findViewById(R.id.listViewMain);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sp = sharedPreferences.edit();
String et1 = sharedPreferences.getString("et1", DEFAULT);
String et2 = sharedPreferences.getString("et2", DEFAULT);
String et3 = sharedPreferences.getString("et3", DEFAULT);
String et4 = sharedPreferences.getString("et4", DEFAULT);
if (et1.equals(DEFAULT) || et2.equals(DEFAULT) || et3.equals(DEFAULT) || et4.equals(DEFAULT))
{
Toast.makeText(this, "No history found", Toast.LENGTH_LONG).show();
}
else
{
String [] values = new String[]{et1,et2,et3,et4};
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, values);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
sp.apply();
}
}
}
The problem I am facing is that I am only seeing one listview with only 1 value being displayed which is obvious as there is no code which does incrementation. When I enter a new value the old value gets overridden. As there are two buttons associated with saveHistory method I am only able to get one value as there is only one listview. So my needs are that I want to store more than one value using sharedpreferences and also clicking on both buttons should save the values and not override each other's value. I know that I am asking too much, but if you can help me find out how to correctly do incrementation with this scenario and with this code, then I would be grateful.
I have gone through many stackoverflow questions and most of them are associated with having one edittext and one button and storing and retrieving those value. However, My application requirements are different, and, as a result, I have posted this question.
You are retrieving the EditTexts values but you are putting something else in your sharedPreferences.
Replace your saveHistory() code with this:
private void saveHistory(){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
fd = sharedPreferences.edit();
String bt = et1.getText().toString();
String an = et2.getText().toString();
String cn = et3.getText().toString();
String in = et4.getText().toString();
fd.putString("et1" , bt); //These lines were the problem
fd.putString("et2" , an); //These lines were the problem
fd.putString("et3" , cn); //These lines were the problem
fd.putString("et4" , in); //These lines were the problem
fd.apply();
}
Edit: I'm sorry I think that I understand your question now.
You can store multiple String values with a single SharedPreferences key with PutStringSet(). You need to make the validation of what button is calling the saveHistory() and then create a Set with this info.
Check the link below for an example.
https://stackoverflow.com/a/9054240/2503185
In your case, you would put something like (for each EditText value):
Set<String> faveSet = faves.getStringSet("et1");
faveSet.add(button + ":" + et1_value);
SharedPreferences.Editor editor = faves.edit();
editor.putStringSet("et1", faveSet);
editor.commit();
And then retrieve that and validate each EditText.
I have a listView in Activity A , which the value are returned from Activity B.When the list is clicked, it will intent to Activity B for edit.
Activity B
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_details_information);
addItemsOnSpinner();
if(getIntent().getExtras()!=null) // if has value pass from A
{
final String Project1=getIntent().getStringExtra("ReceiveProject");
final String Description1=getIntent().getStringExtra("ReceiveDescription");
final String Progress1=getIntent().getStringExtra("ReceiveProgress");
final String TimeIn1=getIntent().getStringExtra("ReceiveTimeIn");
final String TimeOut1=getIntent().getStringExtra("ReceiveTimeOut");
//project.setText(Project1);
description.setText(Description1);
//progressText.setText("Covered:")
timeIn.setText(TimeIn1);
timeOut.setText(TimeOut1);
}
save.setOnClickListener(new View.OnClickListener()
{ // return to A
#Override
public void onClick(View v)
{
Intent returnIntent=new Intent();
Project=project.getSelectedItem().toString(); // Spinner Value
Description=description.getText().toString(); //from editText
progress=seekBar.getProgress(); // From SeekBar
returnIntent.putExtra("Project",Project);
returnIntent.putExtra("Description", Description);
returnIntent.putExtra("progress", progress);
Toast.makeText(getApplicationContext(), progress+"", Toast.LENGTH_LONG).show();
returnIntent.putExtra("TimeIn", TimeIn);
returnIntent.putExtra("TimeOut",TimeOut);
setResult(Activity.RESULT_OK,returnIntent);
finish();
}
});
public void addItemsOnSpinner()
{
project=(Spinner)findViewById(R.id.SpinnerProject);
List<String> list = new ArrayList<String>();
list.add("TRN-XXX-XXX");
list.add("Pro-XXX-XXX);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.spinner_item, list);
//adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
project.setAdapter(adapter);
}
Activity A
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { // if listView is clicked
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
mClickedPosition = position;
Intent i = new Intent(getApplication(), Add_Details_Information.class);
i.putExtra("ReceiveProject", ReceiveProject);
i.putExtra("ReceiveDescription", ReceiveDescription);
i.putExtra("ReceiveProgress", ReceiveProgress);
i.putExtra("ReceiveTimeIn", ReceiveTimeIn);
i.putExtra("ReceiveTimeOut", ReceiveTimeOut);
startActivityForResult(i,PROJECT_REQUEST_CODE);
}
});
}
I know that we can use setText to display the passed value from A to B for editText, but how about the spinner and seekBar value ?
This is the listView in Activity A. Value are returned from Activity B.
When listView is clicked, it will goes to B again to edit.
So how can I make the spinner in B display Pro-XXX-XXX and the seekBar goes to 48 ? Any idea or suggestion ? Thanks a lot
Edited
After used the answer from #Clairvoyant, now I get this (for spinner value).
Activity A
There are 4 list in Activity A.
Assume first list is clicked.
Everything works fine just the spinner(Project/Service/Training) display wrong value. It display the spinner value from last list(PRO-SKM-D5) instead of itself(Pro-XXX-XXX)
First Step: Make your addItemsOnSpinner like as below:
public void addItemsOnSpinner(String value)
{
int position = 0;
project=(Spinner)findViewById(R.id.SpinnerProject);
List<String> list = new ArrayList<String>();
list.add(position,"TRN-XXX-XXX");
list.add("Pro-XXX-XXX");
for(int i=0; i<list.size() ; i++){
if(list.get(i).equalsIgnoreCase(value)){
position = i;
break;
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String> (getApplicationContext(),R.layout.spinner_item, list);
//adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
project.setAdapter(adapter);
project.setSelection(position);
}
Second Step: call the above method when you are assigning value to the variable you have to show in spinner here for eg: project1 is the string value which you want to show in spinner then call the method as follows:
final String Project1=getIntent().getStringExtra("ReceiveProject");
addItemsOnSpinner(Project1);
Use SharedPreferences. Next time, googling helps.
Get SharedPreferences
SharedPreferences prefs = getDefaultSharedPreferences(context);
Read preferences:
String key = "test1_string_pref";
String default = "returned_if_not_defined";
String test1 = prefs.getString(key, default);
To edit and save preferences
SharedPreferences.Edtior editor = prefs.edit(); //Get SharedPref Editor
editor.putString(key, "My String");
editor.commit();
Shorter way to write
prefs.edit().putString(key, "Value").commit();
Additional info for SharedPreferences: JavaDoc and Android Developers Article
I'm using Shared Preferences to save data from an AutoCompleteTextView.
When the user writes something in this AutoCompleteTextView, he can click a button in order to save what he just wrote (so that he doesn't have to write it every time).
Here's what my code looks like:
private AutoCompleteTextView autoComplete = null;
String nameFile = "Web service data";
String myData = "";
SharedPreferences pref;
Editor editor;
String channel = "";
String[] valuesArray = {channel};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
editor = pref.edit();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, valuesArray);
autoComplete = (AutoCompleteTextView) findViewById(R.id.autocompletion);
autoComplete.setAdapter(adapter);
Button add = (Button) findViewById(R.id.add);
add.setOnClickListener(sendForm2);
Button remove = (Button) findViewById(R.id.remove);
remove.setOnClickListener(sendForm2);
channel = pref.getString(nameFile, null);
}
OnClickListener sendForm2 = new OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.add:
myData = autoComplete.getText().toString();
editor.putString(nameFile, myData);
editor.commit();
break;
case R.id.remove:
editor.remove(nameFile);
editor.commit();
break;
}
}
};
The problem is, the Shared Preferences doesn't save any data in channel at all. Even when I close the application and restart it.
Any clue or idea how to resolve this problem?
First thing I would try would be to add a
Log.d("OnCreate", "channel : "+ channel);
in the onCreate just after
channel = pref.getString(nameFile, null);
to see if you have something inside.
If you don't, this really means that sharedpref are not saved.
In this case I would try to bring back the :
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
editor = pref.edit();
just before the
switch (v.getId()) {
I remember reading that sometimes depending on what you are doing with your activities, the sharedpref editor you create can be "lost" and not be related to anything later in the code.
Use the following method to save and retrive String prefrence.
//save the prefrence by pasing key and data
public static void SavePrefrence(Context ctx, String Key, String value) {
ctx.getSharedPreferences("mypref", ctx.MODE_PRIVATE)
.edit().putString(Key, value).commit();
}
//get the prefrence by passing your key
public static String getPrefrence(Context ctx, String key) {
SharedPreferences pref = ctx.getSharedPreferences(
"mypref", ctx.MODE_PRIVATE);
String result = pref.getString(key, null);
return result;
}
I have a listview with textviews that bring information from a table in sql server as id, description and quantity. I need that when the user clicks on an item in the listview, open another activity with that information that the user selected, the user can edit and save in the database.
I have the following code that queries the database and fills the listview, but I can't find the way to pass the information to another activity. Any help?
public void getProd() {
comandSQL = "Select * from Inventory where [Code] = '"+loccode+"' order by [Bin Code]";
try {
Statement statement = MainActivity.connect.createStatement();
rs = statement.executeQuery(comandSQL);
List<Map<String, String>> data = null;
data = new ArrayList<Map<String,String>>();
while(rs.next()){
Map<String, String> datanum = new HashMap<String, String>();
datanum.put("idProd", rs.getString("No_"));
datanum.put("desc", rs.getString("Description"));
datanum.put("ubic", rs.getString("Bin Code"));
datanum.put("cant", rs.getString("Inventory"));
data.add(datanum);
}
String[] from = {"idProd","desc","ubic","cant"};
int[] views = {R.id.id_prod,R.id.descripcion, R.id.ubicacion,R.id.cant};
AD = new SimpleAdapter(this, data, R.layout.list, from, views);
Lista.setAdapter(AD);
} catch (Exception e) {
Log.e("ERROR",e.getMessage());
}
}
You want to set up a click listener for each listview item:
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Do something when a list item is clicked
}
When the item is clicked, you need to gather the data from that view and then simply start a new activity passing that data via an Intent
Intent intent = new Intent(mContext, YourNewActivity.class);
intent.putExtra("MyData", userData.toString());
startActivity(intent);
Here is the code:
ibtSearchStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try{
searchQuery = etSearchThis.getText().toString();
searchQuery = searchQuery.toUpperCase();
cursor = searchActivity.getData(product, "product", tableColumns);
//Clean ArrayList
resultRow.clear();
resultTable.clear();
//Get Search Result
resultTable = searchActivity.searchByProductName(cursor, searchQuery);
//Display Search Result
for(int ctr = 0; ctr < resultTable.size(); ctr++){
HashMap<String, String> map = new HashMap<String, String>();
resultRow = resultTable.get(ctr);
String result = resultRow.get(2);
map.put("ProductName",result);
list.add(map);
}
Log.e("resultProduct", "" + list);
adapter = new SimpleAdapter(
SearchMain.this,
list,
R.layout.search_result,
new String[]{"ProductName"},
new int[]{R.id.tvProductName}
);
lvSearchResult.setAdapter(adapter);
}
finally{
product.close();
}
}
});
The function of this is that it will search for a match in the database then it will insert the result of the search in a HashMap then on a adapter.
But every click i am not able to remove the previous result.
What is the proper implementation to this?
When you are working with adapters and the information changes, be sure that you are calling adapter.notifyDataSetChanged();
You set a new adapter each time the OnClick event is triggered. As Jay Snayder wrote you should use adapter.notifyDataSetChanged(); instead. But be sure to set the adapter only once and move the following part of your code (e.g. to your onCreate() method of the activity):
adapter = new SimpleAdapter(
SearchMain.this,
list,
R.layout.search_result,
new String[]{"ProductName"},
new int[]{R.id.tvProductName}
);
lvSearchResult.setAdapter(adapter);
Just update the DataSet of your adapter (here: 'list').