in my android application I have a Button which adds a new dynamic Spinner to the Layout. All of the created Spinners are using the same Array.
What is working until now, I can save the number of created Spinners and recreate them after restarting the Application.
But I really would like to save the selectedPosition of each Spinner in the sharedPreferences and this is where I'm stucking in a ForceClose Desaster...
In my understanding, every Spinner gets an ID when created so you can save the Position bounded on this ID in the preferences.
So this is what I did:
public void addSpinner(){
LinearLayout AddLayout = (LinearLayout)findViewById(R.id.linearAddScroll);
spinner = new Spinner(this);
ArrayAdapter<?> adapt = ArrayAdapter.createFromResource(this,
R.array.Filter, android.R.layout.simple_spinner_item);
adapt.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapt);
AddLayout.addView(spinner);
}
this creates the Spinner.
public void onClick(View v) {
addSpinner();
int ID = 1000+x;
spinner.setId(ID);
Toast.makeText(MatReporterActivity.this,"ID" + ID, 5)
.show();
x++;
}
set the ID.
This is what I do in the on Create method:
x = settings.getInt("xsave", 1);
for(y = 1; y < x; y++){
addSpinner();
int ID = 1000+y;
Spinner s = (Spinner) findViewById(ID);
String ys= Integer.toString(ID);
Toast.makeText(MatReporterActivity.this,"ID" +ys, 5)
.show();
int yf = settings.getInt(ys, 1);
s.setSelection(yf);
}
And this onStop():
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("xsave", x);
for(y = 1; y < x; y++){
int ID = 1000+y;
Spinner s2= (Spinner) findViewById(ID);
int possS = s2.getSelectedItemPosition();
Toast.makeText(MatReporterActivity.this, "IDStop" + ID, 5)
.show();
String ys= Integer.toString(ID);
editor.putInt(ys, possS);
}
editor.commit();
}
I think there is a logical Problem in the onCreate Method, but I'm not able to find it, also I didn't find any help in the web how to populate and save dynamically created spinners.
So maybe someone has an idea.
thanks.
SharedPreferences are not a good way to store this kind of data. You should try to follow those 2 steps :
Create a class which implements Serializable to represent the data you want to store (you might use a list of Serializable objects)
public class SpinnerSave implements Serializable {
public String ID;
public int selection;
public SpinnerSave(String ID, int selection){
this.ID = ID;
this.selection = selection;
}
}
Then you should write your data into a file like so
private void saveState() {
final File cache_dir = this.getCacheDir();
final File suspend_f = new File(cache_dir.getAbsoluteFile() + File.separator + SUSPEND_FILE);
FileOutputStream fos = null;
ObjectOutputStream oos = null;
boolean keep = true;
try {
fos = new FileOutputStream(suspend_f);
oos = new ObjectOutputStream(fos);
oos.writeObject(this.gameState);
}
catch (Exception e) {
keep = false;
Log.e("MyAppName", "failed to suspend", e);
}
finally {
try {
if (oos != null) oos.close();
if (fos != null) fos.close();
if (keep == false) suspend_f.delete();
}
catch (Exception e) { /* do nothing */ }
}
}
Related
Hi i have been working on a project where i have to make a plus button and onclick of that plus button a i'm inflating a new layout which consits of two editext and one remove image.
So far it is working as expected but the problem is that when i click on remove image editext of that particular row is removed however the data is still being sent to database.
I tried using remove method of arraylist but still it is not working.
So please could someone help me out here.
Here is my code for layout inflation
public void makedifferentEditText() {
try {
View secondchild = getLayoutInflater().inflate(R.layout.update_extra_links_layout, null);
final LinearLayout update_extra_links_layout = (LinearLayout) secondchild.findViewById(R.id.update_extra_links_layout);
customtextTitle = (CustomEditTextThin) secondchild.findViewById(R.id.google_edit_link);
customeditTextLink = (CustomEditTextThin) secondchild.findViewById(R.id.facebook_edit_link);
eexId = (TextView) secondchild.findViewById(R.id.eeid);
google_tilte.add(customtextTitle);
google_link.add(customeditTextLink);
extId.add(eexId);
Log.e("title", google_tilte.toString());
Log.e("link", google_link.toString());
AppCompatImageView removeimage = (AppCompatImageView) secondchild.findViewById(R.id.icon_remove_link);
rAlign.addView(update_extra_links_layout);
int indexValue = rAlign.indexOfChild(update_extra_links_layout);
update_extra_links_layout.setTag(indexValue);
int ImagePosition = rAlign.indexOfChild(update_extra_links_layout);// update_extra_links_layout.indexOfChild(removeimage);
removeimage.setTag(ImagePosition);
removeimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
int index = (int) view.getTag();
// if (index != -1) {
if (rAlign.getChildCount()>1) {
// int index = rAlign.indexOfChild(update_extra_links_layout);
rAlign.removeViewAt(index);
google_tilte.remove(index);
google_link.remove(index);
extId.remove(index);
//customtextTitle.setText("");
//customeditTextLink.setText("");
}
//}
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
and Here is the code for adding data to database
if (google_link != null && google_link.size() > 0) {
for (int j = 0; j < google_link.size(); j++) {
/*arrayTitle.add(google_link.get(j).getText().toString());
Log.e("array", arrayTitle.toString());*/
ExtraLinksObject links4 = new ExtraLinksObject();
String othergoogleTitle = google_tilte.get(j).getText().toString();//customtextTitle.getText().toString();
String othergooglelink = google_link.get(j).getText().toString();//customeditTextLink.getText().toString()
String googleId = extId.get(j).getText().toString();//eexId.getText().toString();
links4.setLink(othergooglelink);
links4.setTitle(othergoogleTitle);
links4.setExID(googleId);
extraLinks.add(links4);
}
}
Accepting data from database and displaying it on Table Layout and using that data creating a piechart with MpAndroidChart Library but getting the error as stated above
I am transfering arraylist from one activity to other using putextra and getSerializableExtra while accepting "the error is shown as above"
I am sharing my code please help
yValue is my arraylist where data is stored
transfering it to mylist using intent but this is generating error
My code:-
public class DisplayDate extends MainActivity{
public ArrayList<PieEntry> yValues = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_date);
doInBackground();
pieChart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent pieIntent = new Intent(DisplayDate.this,DisplayPiechart.class);
pieIntent.putExtra("Pie Values",yValues);
startActivity(pieIntent);
}
});
}
public void doInBackground()
{
ConnectionHelper connectString = new ConnectionHelper();
connect = connectString.connectionClass();
Log.w("Android","Connecting....");
if (connect == null)
{
Log.w("Android","Connection Failed");
ConnectionResult = "Check Your Internet Connection";
}
else
{
Log.w("Android","Connected");
String query = "Select No_,Name,Date,[Net Amount],[Gross Amount] from [CRONUS LS 1010 W1 Demo$Store] as str,[CRONUS LS 1010 W1 Demo$Transaction Header] as trans where str.[No_] = trans.[Store No_] and trans.[Date] between '"+Actual_Start+"' and '"+Actual_End+"' ";
try
{
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery(query);
Log.w("Android","database Connected");
while (rs.next()) {
TR = new TableRow(this);
TV1.setText(rs.getString("No_"));
TV2.setText(rs.getString("Name"));
TV4.setText(rs.getString("Date"));
TV5.setText(rs.getString("Net Amount"));
TV3.setText(rs.getString("Gross Amount"));
TL.addView(TR);
c = TV3.getText().toString();
a = Float.parseFloat(c);
d = TV1.getText().toString();
yValues.add(new PieEntry(a,d));
}
ConnectionResult = "Successful";
isSuccess = true;
connect.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
class DisplayPiechart extends DisplayDate{
com.github.mikephil.charting.charts.PieChart pieChart;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_piechart);
Intent i = getIntent();
ArrayList<PieEntry> myList = (ArrayList<PieEntry>) i.getSerializableExtra("Pie Values");
//Error at below line
PieDataSet dataSet = new PieDataSet(myList, "Stores");
dataSet.setSliceSpace(2f);
dataSet.setSelectionShift(6f);
dataSet.setColors(ColorTemplate.MATERIAL_COLORS);
PieData data = new PieData(dataSet);
data.setValueTextSize(10f);
data.setValueTextColor(Color.BLACK);
pieChart.setData(data);
}
}
This is a very old question but was running into the same issue. I'm new at this so take it with a grain of salt. There is probably a better way of solving it but posting it in case it helps someone.
I solved it by creating an ArrayList in the receiving activity as such:
ArrayList<Entry> receivedData;
receivedData = new ArrayList<>();
Then stored the data passed from the first activity into this ArrayList:
receivedData = getIntent().getParcelableArrayListExtra("data");
// Get size of ArrayList
int size = receivedData.size();
// Getting individual X and Y values from each ArrayList element
for(int k = 0; k < size; k++){
// Adding X and Y values as entries in a different
// ArrayList barEntriesArrayList
addDataPointsToGraph((int) receivedData.get(k).getX(), receivedData.get(k).getY());
}
And here is that Method:
private void addDataPointsToGraph(int x, float y){
barEntriesArrayList.add(new BarEntry(x, y));
}
I then supplied this ArrayList barEntriesArrayList to the dataSet
// creating a new bar data set.
barDataSet2 = new BarDataSet(barEntriesArrayList, getResources().getString(R.string.valuePerDay));
I was using these two tutorials as a guide when generating my graph
https://www.geeksforgeeks.org/how-to-create-a-barchart-in-android/
https://learntodroid.com/how-to-display-a-bar-chart-in-your-android-app/
I have an issue with renaming a file it seems every time I try to they end up being multiplied and are created 2 times the amount I.e. if I have one song that I want to rename in the list view and hold the on long click event it doubles the amount say 2 to 4 songs and 4 to 12 and so on in my list view . I'm using an OnItemLongClickListener to handle the files being created for each item click on the list view to be renamed . I have no idea why it isn't working ... I have even tried setting the position to
String pos = lv.getItemAtPosition(position);
And many other ways ...
But no use it ends up being a random number that is being multiplied ... My question is why ; how can fix .
downloadsList.setOnItemLongClickListener(
new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> parent , View view , int position , long itemId ){
EditText bar = (EditText)findViewById(R.id.search);
String to = bar.getText().toString();
(ListView) findViewById(R.id.downloads);
File[] pos = files.listFiles();
File filein = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() , files.getName());
File fileTo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/" + to);
if(!filein.exists()){
filein.renameTo(fileTo);
} else {
try {
throw new IOException("File exists");
}catch (IOException e){
e.printStackTrace();
}
}
finish();
overridePendingTransition(0, 0);
startActivity(getIntent());
overridePendingTransition(0, 0);
return true;
}
});
Here is the list view method to populate it
private void ShowLists(){
files = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DOWNLOADS).toString());
downloads = files.listFiles(new FileFilter(){
#Override
public boolean accept(File file){
String ext = file.getName();
if(ext.endsWith(".mp3")){
return true;
}
return false;
}
});
mp3s = new String[downloads.length];
for(int i = 0 ; i < mp3s.length; i++){
mp3s[i] = downloads[i].getName();
}
adapter = new ArrayAdapter<String>(this,R.layout.downloads, R.id.textviewone , mp3s);
ListView downloadsList = (ListView) findViewById(R.id.downloads);
downloadsList.setAdapter(adapter);
}
This is before http://imgur.com/rBmSAXK
This is after I click the long click to rename a file and the on going complication http://imgur.com/I9szC6m
UPDATED CODE
public boolean onItemLongClick(AdapterView<?> parent , View view , int position , long itemId ){
EditText bar = (EditText)findViewById(R.id.search);
String to = bar.getText().toString();
ListView lv = (ListView) findViewById(R.id.downloads);
String pos = lv.getItemAtPosition(position).toString();
File filein = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() , pos);
File fileTo = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() , to);
filein.renameTo(fileTo);
finish();
overridePendingTransition(0, 0);
startActivity(getIntent());
overridePendingTransition(0, 0);
return true;
}
});
I have created an array. I want to be able to save it and have it load when the app is closed from memory. . I did some research and found you can use use these commands: SaveArrayListToSD and ReadArrayListFromSD.
However, I don't know how to relate these to the rest of my code...
How do I save and load the array when the app is opened/closed?
After further research, I have changed my mind about the SQLite database - I don't mind using it if it's easier. If I was to use an SQLite database, how would I go about saving my arraylist into the database?
Code:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) { //Rendering the UI
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView myListView = (ListView)findViewById(R.id.myListView);
final EditText myEditText = (EditText)findViewById(R.id.myEditText);
//Creating Array of Strings
final ArrayList todoItems = new ArrayList();
final ArrayAdapter aa;
aa = new ArrayAdapter(this,android.R.layout.simple_list_item_1,
todoItems);
myListView.setAdapter(aa);
myEditText.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN)
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER){
todoItems.add(0, myEditText.getText().toString());
aa.notifyDataSetChanged();
return true;
}
return false;
}
});
}
public static void SaveArrayListToSD(Context mContext, String savedArray, ArrayList todoItems) {
try {
FileOutputStream fos = mContext.openFileOutput(savedArray + ".dat", mContext.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(todoItems);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Object ReadArrayListFromSD(Context mContext,String savedArray){
try {
FileInputStream fis = mContext.openFileInput(savedArray + ".dat");
ObjectInputStream ois = new ObjectInputStream(fis);
Object obj= (Object) ois.readObject();
fis.close();
return obj;
} catch (Exception e) {
e.printStackTrace();
return new ArrayList<Object>();
}
}
}
You can use internal storage to save the strings in you ArrayList. Here is more info on using internal storage. You can write the data in onStop or onDestory and read the data in onCreate.
Well i can write you simple example for you.
initialise SQLite
SQLiteDatabase db = db=openOrCreateDatabase("yourDBName", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS Employee(id VARCHAR,name VARCHAR,email VARCHAR);");
db.execSQL("INSERT INTO student VALUES('"+idField.getText()+"','"+nameTextfield.getText()+"','"+emailtextfield.getText()+"');");
db.execSQL("DELETE FROM Employee WHERE id='"+idField.getText()+"'");
db.execSQL("UPDATE Employee SET name='"+nameTextfield.getText()+"',email='"+emailTextfield.getText()+"'WHERE id='"+idField.getText()+"'");
And to Select from database please follow this
Cursor c=db.rawQuery("SELECT * FROM Employee WHERE id='"+idField.getText()+"'", null);
if(c.moveToFirst()){
//String id = c.getString(0);
String name = c.getString(1);
String email = c.getString(2);
}
I have been trying to find answers, but it has been hard to find a solution that works.
I tried setting the adapter to null, clearing the actual list but neither seems to work.
I am using a ListView with a ListAdapter and am trying to make it clear on a change of search Text when text is changed.
list.clear(); works but it does not occur on text change.
Here is my code:
private EditText search_input;
private Button search_button;
// progress bar for search results
private ProgressDialog search_loading;
private ListView wordSearchList;
private ListAdapter adapter;
// no result layout
private LinearLayout no_res;
// create list for adapter
ArrayList<HashMap<String, String>> list;
// database helper
private DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dictionary_search);
search_input = (EditText) findViewById(R.id.search_dictionary);
search_button = (Button) findViewById(R.id.search_button);
search_button.setOnClickListener(this);
// linear layout for no results
no_res = (LinearLayout) findViewById(R.id.search_result_ll);
// create hashmap list
list = new ArrayList<HashMap<String, String>>();
// remove views if they exist
search_input.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// REMOVE LIST VIEW AND ADAPTER
// list.clear();
if (no_res.getChildCount() > 0) {
no_res.removeAllViews();
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
#Override
public void onClick(View v) {
if (v == search_button) {
// clear list for fresh start
list.clear();
no_res.removeAllViews();
// validate input and that something was entered
if (search_input.getText().toString().length() < 1) {
// missing required info (null was this but lets see)
Toast.makeText(getApplicationContext(),
"Please search for something!", Toast.LENGTH_LONG)
.show();
} else {
String search_data;
search_data = search_input.getText().toString();
// remove any current views on search again
// REMOVE THE LIST VIEW
// execute the query search
List<DatabaseWordsFTS> search_results = db
.getSingleWordSearch(search_data);
// if no search results returned
if (search_results.size() <= 0) {
TextView no_results_tv = new TextView(this);
no_results_tv.setText("No results found.");
no_res.addView(no_results_tv);
}
// setup listview
wordSearchList = (ListView) findViewById(R.id.wordSearchList);
for (DatabaseWordsFTS word_found : search_results) {
// have to create hashmap in loop
HashMap<String, String> map = new HashMap<String, String>();
// convert d id to long
Integer dictionary_id_convert = (int) (long) word_found._dictionaryId;
// extract dictionary from d-id - since it is not a list and
// just a variable
DatabaseDictionary dictionary_found = db
.getDictionary(dictionary_id_convert);
// extract languages to send below
Integer dln_1 = (int) dictionary_found._language1Id;
Integer dln_2 = (int) dictionary_found._language2Id;
Integer dln_3 = (int) dictionary_found._language3Id;
Integer dln_4 = (int) dictionary_found._language4Id;
// get languages for the words based on ids passed in
List<DatabaseLanguages> LanguagesForD = db
.getAllLanguagesWithId(dln_1, dln_2, dln_3, dln_4);
// add name to hashmap and rest of the data as strings
map.put("w_1", word_found.get_word1_fts());
map.put("l_1", LanguagesForD.get(0)._language_name);
map.put("d_id", String.valueOf(dictionary_id_convert));
map.put("w_id", String.valueOf(word_found.get_id()));
if (word_found.get_word2_fts() != null) {
map.put("w_2", word_found.get_word2_fts());
map.put("l_2", LanguagesForD.get(1)._language_name);
}
if (word_found.get_word3_fts() != null) {
map.put("w_3", word_found.get_word3_fts());
map.put("l_3", LanguagesForD.get(2)._language_name);
}
if (word_found.get_word4_fts() != null) {
map.put("w_4", word_found.get_word4_fts());
map.put("l_4", LanguagesForD.get(3)._language_name);
}
list.add(map);
// used to dismiss progress bar for searching
search_loading.dismiss();
}
String[] from = { "w_1", "w_2", "w_3", "w_4" }; // , "word3",
// "word4"
int[] to = { R.id.textName, R.id.textLanguage };
adapter = new SimpleAdapter(this, list,
R.layout.dictionary_row, from, to);
wordSearchList.setAdapter(adapter);
wordSearchList
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
HashMap itemValue = (HashMap) wordSearchList
.getItemAtPosition(position);
String w_id = (String) itemValue.get("w_id");
String d_id = (String) itemValue.get("d_id");
String l_1 = (String) itemValue.get("l_1");
String l_2 = (String) itemValue.get("l_2");
String l_3 = (String) itemValue.get("l_3");
String l_4 = (String) itemValue.get("l_4");
String w_1 = (String) itemValue.get("w_1");
String w_2 = (String) itemValue.get("w_2");
String w_3 = (String) itemValue.get("w_3");
String w_4 = (String) itemValue.get("w_4");
// Show Alert
Toast.makeText(
getApplicationContext(),
"Position :" + itemPosition
+ " ListItem : " + w_id,
Toast.LENGTH_LONG).show();
// creating bundle
Bundle d_data = new Bundle();
// add to bundle
d_data.putString("w_id", w_id);
d_data.putString("wd_id", d_id);
d_data.putString("w_1", w_1);
d_data.putString("l_1", l_1);
// get tags only if it exists
if (w_2 != null) {
d_data.putString("w_2", w_2);
d_data.putString("l_2", l_2);
}
if (w_3 != null) {
d_data.putString("w_3", w_3);
d_data.putString("l_3", l_3);
}
if (w_4 != null) {
d_data.putString("w_4", w_4);
d_data.putString("l_4", l_4);
}
// start new intent based on the tag -
Intent single_word_view = new Intent(
DictionaryWordSearch.this,
DictionarySingleWordView.class);
// call extras
single_word_view.putExtras(d_data);
// new_dictionary_view.putExtra("d_id",
// WhatAmISupposeToPassInHere);
startActivity(single_word_view);
}
});
}
EDIT: (Below worked for me)
Changed ListAdapter to SimpleAdapter
if(adapter != null){list.clear(); adapter.notifyDataSetChanged();}
Added the above code in onTextChange
Look if you want the TextView with no result you can implement this code
listView.setEmptyView(emptyView)
and pass your TextView to this method ,
for clearing the ListView you can clear your collection and call notifyChangeDataSet or set adapter with null try both and feed me back