I have one class that shows me a list of Items. Right now I am selecting this items with click (setOnItemClickListener), but i don't want that. What i want is: when i open the class automatically is selecting the last item on the list.
Can anyone tell me how I can do it?
Thanks for any help
public class SelectCodIncidence extends Activity {
private ArrayList<String> datos;
protected netAppApplication app;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.codincidence);
datos = new ArrayList<String>();
//datosCod = new ArrayList<String>();
try {
NotesCenter messageCenter = new NotesCenterImpl();
List<CodIncidence> codincidence = messageCenter.getCodIncidence();
for (CodIncidence e : codincidence) {
//datosCod.add("1");
datos.add(e.id);
}
} catch (Exception ex) {
// showMessage(ex);
Log.v("blah", ex.getMessage());
}
ArrayAdapter<String> adaptador =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, datos);
final TextView lblMessage = (TextView)findViewById(R.id.MensajeCodIncidence);
final GridView grdOptions = (GridView)findViewById(R.id.GridCodIncidence);
grdOptions.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, android.view.View v, int position, long id) {
CodIncidence codincidenceSelected = new CodIncidence();
codincidenceSelected.id = datos.get(position);
app = (netAppApplication)getApplicationContext();
app.setcodincidenceActual(codincidenceSelected);
SharedPreferences prefs = getSharedPreferences("netAppSetup",2);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("CODINCIDENCE", codincidenceSelected.id);
editor.commit();
finish();
}
});
grdOptions.setAdapter(adaptador);
}
}
Something like:
Spinner spinner = (Spinner) findViewById(R.id.mySpinner);
int count = spinner.getCount();
if (count > 0){
spinner.setSelection(count-1,true);
}
Related
I have currently implemented a listview, which when you click an item opens a second activity. In the second activity I have another listview which i can add items to, but when i go back to the first list and click another item, all the items from the second list appear for this one as well.
Any ideas how to sort this out? Can post code if needed
Here is the code for the first activity:
public class MainActivity extends Activity {
private ArrayList<String> entries;
private ArrayAdapter<String> entriesAdapter;
private ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createListView();
createListViewListener();
}
private void createListView() {
list = (ListView) findViewById(R.id.diaryListView);
entries = new ArrayList<>();
readEntries();
entriesAdapter = new CustomAdapter(this, entries);
list.setAdapter(entriesAdapter);
}
private void createListViewListener() {
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
entries.remove(position);
entriesAdapter.notifyDataSetChanged();
writeEntries();
return true;
}
});
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("entry", entries.get(position));
startActivity(intent);
}
});
}
public void addEntry(View v) {
EditText entryEditText = (EditText) findViewById(R.id.entryEditText);
String diaryText = entryEditText.getText().toString();
entriesAdapter.add(diaryText);
entryEditText.setText("");
writeEntries();
}
private void readEntries() {
File filesDir = getFilesDir();
File journalEntriesFile = new File(filesDir, "journalEntries.txt");
try {
entries = new ArrayList<>(FileUtils.readLines(journalEntriesFile));
} catch (IOException e) {
entries = new ArrayList<>();
}
}
/**
* Method to save a list of tasks
*/
private void writeEntries() {
File filesDir = getFilesDir();
File journalEntriesFile = new File(filesDir, "journalEntries.txt");
try {
FileUtils.writeLines(journalEntriesFile, entries);
} catch (IOException e) {
e.printStackTrace();
}
}
and the second:
public class SecondActivity extends Activity {
private String entryName;
private TextView entryTitle;
private ArrayList<String> entryTask;
private ArrayAdapter<String> entryTaskAdapter;
private ListView entryTaskList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
displayEntryTitle();
createEntryTaskListView();
createEntryTaskListViewListener();
}
private void displayEntryTitle() {
entryTitle = (TextView) findViewById(R.id.entryTitle);
Intent intent = getIntent();
entryName = intent.getStringExtra("entry");
entryTitle.setText("" + entryName);
}
private void createEntryTaskListView() {
entryTaskList = (ListView) findViewById(R.id.entryTaskListView);
entryTask = new ArrayList<>();
readEntryTasks();
entryTaskAdapter = new CustomAdapter2(this, entryTask);
entryTaskList.setAdapter(entryTaskAdapter);
}
private void createEntryTaskListViewListener() {
entryTaskList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
entryTask.remove(position);
entryTaskAdapter.notifyDataSetChanged();
writeEntryTasks();
return true;
}
});
entryTaskList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
View view2 = (LayoutInflater.from(SecondActivity.this)).inflate(R.layout.alert_dialog, null);
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(SecondActivity.this);
alertBuilder.setTitle("Edit Journal Task Entry");
alertBuilder.setView(view2);
final EditText editEntryTaskText = (EditText) view2.findViewById(R.id.editEntryTask);
alertBuilder.setCancelable(true).setPositiveButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String editEntry = editEntryTaskText.getText().toString();
editEntryTaskText.setText("" + editEntry);
}
});
Dialog dialog = alertBuilder.create();
dialog.show();
}
});
}
public void onAddEntryTask(View v) {
EditText editText = (EditText) findViewById(R.id.entryTaskEditText);
String entryTaskText = editText.getText().toString();
entryTaskAdapter.add(entryTaskText);
editText.setText("");
writeEntryTasks();
}
private void readEntryTasks() {
File filesDir = getFilesDir();
File taskEntriesFile = new File(filesDir, "taskEntries.txt");
try {
entryTask = new ArrayList<>(FileUtils.readLines(taskEntriesFile));
} catch (IOException e) {
entryTask = new ArrayList<>();
}
}
private void writeEntryTasks() {
File filesDir = getFilesDir();
File taskEntriesFile = new File(filesDir, "taskEntries.txt");
try {
FileUtils.writeLines(taskEntriesFile, entryTask);
} catch (IOException e) {
e.printStackTrace();
}
}
Without seeing how you get back to the first activity from the second activity I can only assume that ArrayList entrytask is getting inserted into ArrayList entries when you return so based on the limited information I have the best answer I can come up with is
private void createListView() {
list = (ListView) findViewById(R.id.diaryListView);
entries = new ArrayList<>();
list.setAdapter(null);
//ArrayList<String> entries = null;
readEntries();
entriesAdapter = new CustomAdapter(this, entries);
list.setAdapter(entriesAdapter);
}
I have a block of code creating arraylists, adapter and onclickitemlistener and it works great ONLY if it is meant to work once. I want to include the block in a loop so it's performed several times, but when I do so the app crashes when I want to go to that activity so the block does not run even once... what may be the reason?
public class MyClass extends Activity {
int c=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.quiz1);
final ArrayList<String> words = new ArrayList<String>();
TextView tvTo = (TextView) findViewById(R.id.tvTo);
ListView lvLV = (ListView) findViewById(R.id.lvLV);
DataWraper dwF = (DataWraper) getIntent().getSerializableExtra("data");
ArrayList<Word> wordList = dwF.GetWords();
for(Word w : wordList) {
words.add(w.GetSth()+"."+w.GetSthElse());
}
// do {
Generator set = new Generator(words);
ArrayList<String> s = set.GetQuizSet();
final String palabra = s.get(0).substring(s.get(0).indexOf(".")+1);
tvTo.setText(s.get(0).substring(0, s.get(0).indexOf(".")));
Collections.shuffle(s);
final ArrayList<String> sp = new ArrayList<String>();
for(String o : s) {
transl.add(o.substring(o.indexOf(".")+1));
}
MAdapter la = new MAdapter(MyClass.this, sp);
lvLV.setAdapter(la);
lvLV.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(sp.get(position).matches(palabra)) {
Toast.makeText(getBaseContext(), "Good", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Not Good", Toast.LENGTH_LONG).show();
}
// c++;
}
});
// } while(c<5);
}
}
Looks like you're getting a StackOverflowError. You only increment c in the OnItemClickListener, so it's not getting incremented in onCreate(), and your while-loop is running endlessly.
Without knowing exactly what you're trying to accomplish, or what exactly all your classes are, I juggled your code a bit. You might want to structure your code more like this:
public class MyClass extends Activity
{
int c = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.quiz1);
final ArrayList<String> words = new ArrayList<String>();
TextView tvTo = (TextView) findViewById(R.id.tvTo);
ListView lvLV = (ListView) findViewById(R.id.lvLV);
DataWraper dwF = (DataWraper) getIntent().getSerializableExtra("data");
ArrayList<Word> wordList = dwF.GetWords();
for (Word w : wordList)
{
words.add(w.GetSth() + "." + w.GetSthElse());
}
final ArrayList<String> sp = new ArrayList<String>();
MAdapter la = new MAdapter(MyClass.this, sp);
lvLV.setAdapter(la);
lvLV.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//*** Your call to generate() will go in here
//*** depending on where you want it
if (sp.get(position).matches(palabra))
{
Toast.makeText(getBaseContext(), "Good", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getBaseContext(), "Not Good", Toast.LENGTH_LONG).show();
}
}
}
);
}
private void generate()
{
if (c < 5)
{
Generator set = new Generator(words);
ArrayList<String> s = set.GetQuizSet();
final String palabra = s.get(0).substring(s.get(0).indexOf(".") + 1);
tvTo.setText(s.get(0).substring(0, s.get(0).indexOf(".")));
Collections.shuffle(s);
for (String o : s)
{
transl.add(o.substring(o.indexOf(".") + 1));
}
c++;
}
}
}
here I have a Fragment, I use this code and everything works normally, and what I want to do is update my shown list if there is a new file, could you guys give any advice or hint?
CODE:
public class HomeFragment extends Fragment {
public static final String TITLE = "title";
private List<String> library = new ArrayList<String>();
private TextView tv;
private ListView lv;
private ArrayAdapter<String> adapter;
public static Handler handHF;
private String[] temp;
private Object UIlock = new Object();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.home_fragment, container,
false);
library = getLibraryList();
if (!library.isEmpty()) {
if (tv != null) {
tv.setVisibility(View.GONE);
} else {
temp = library.toArray(new String[library.size()]);
lv = (ListView) rootView.findViewById(R.id.library_list);
adapter = new ArrayAdapter<String>(rootView.getContext(),
android.R.layout.simple_list_item_1, temp);
lv.setAdapter(adapter);
setListener(lv);
tv = (TextView) rootView.findViewById(R.id.library_tv1);
tv.setVisibility(View.GONE);
tv = null;
}
} else {
tv = (TextView) rootView.findViewById(R.id.library_tv1);
tv.setText("No Manga found...");
}
return rootView;
}
#SuppressLint("HandlerLeak")
#Override
public void onResume() {
/*
* Fragment on pause state
*/
super.onResume();
handHF = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message msg) {
if (msg.what == 0) {
refreshAdapter();
}
}
};
}
private void setListener(ListView lv) {
/*
* Sets listener on listView
*/
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent myIntent = new Intent(view.getContext(),
ChapterActivity.class);
myIntent.putExtra(TITLE, parent.getItemAtPosition(position)
.toString());
startActivity(myIntent);
}
});
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(view.getContext(),
parent.getItemAtPosition(position).toString(),
Toast.LENGTH_SHORT).show();
return true;
}
});
}
private final List<String> getLibraryList() {
/*
* Returns List<String> of library
*/
List<String> l = new ArrayList<String>();
File dir = new File(Constants.UNDUH);
if (dir.exists()) {
File[] dirs = dir.listFiles();
for (File i : dirs) {
l.add(i.getName());
}
return l;
} else {
return l;
}
}
private void refreshAdapter() {
/*
* It will update library and
*/
synchronized (UIlock) {
getActivity().runOnUiThread(new Runnable() {
public void run() {
if (tv != null) {
tv.setVisibility(View.GONE);
}
library = getLibraryList();
temp = library.toArray(new String[library.size()]);
lv = (ListView) getActivity().findViewById(
R.id.library_list);
adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, temp);
lv.setAdapter(adapter);
}
});
}
}
}
any advice will be appreciated, thank you!
Update your list of string which you are passing to the ListView in your case you are using
private String[] temp;
Use notifyDataSetChanged Method, just call this after your adapter and it will automatically adds more items to list if your temp[] increments.
like this
adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, temp);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
Where you are adding more data into temp[]
add an extra line
((ArrayAdapter) lv.getAdapter()).notifyDataSetChanged();
Can anybody tell me the code to reload a Spinner?
I have created a small app where I can add some items and delete unwanted items. The items added will be showed in a spinner. Once I select an item from the spinner and delete it clicking the Delete Button, The item is getting deleted from the database & I get a Toast displayed "Item Deleted". But its still showing in the spinner until I logout and logs in once again. Here, I think I need to reload the spinner once again on the Delete button click. Can anybody help me out to do that?
public class DeleteChildActivity extends Activity {
TextView name;
Button delete;
Spinner spinner2;
private String URL = "/ParentProfileServlet";
private String URL1 = "/ChildProfileServlet";
private String URL2 = "/DeleteChildServlet";
ArrayList<NameValuePair> postparameter;
public static int selectChildId;
public static String imei;
ParentDetailsMod parentModel;
private ArrayList<ChildDetails> childArray = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.delete_child);
delete = (Button) findViewById(R.id.B_delchild);
spinner2 = (Spinner) findViewById(R.id.childspinner);
childArray = new SelectParser().parseSelectXml(response);
ArrayList<String> stringArray = new ArrayList<String>();
for (ChildDetails childModel : childArray) {
String str;
str = childModel.getName();
stringArray.add(str);
}
// spinner = (Spinner) findViewById(R.id.spinner11);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getApplicationContext(), android.R.layout.simple_list_item_1,
stringArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapter);
spinner2.setPrompt(getString(R.string.selectLabel));
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
imei = childArray.get(position).getImei_num();
selectChildId = childArray.get(position).getChild_id();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// spinner.performClick();
// String id = spinner2.getSelectedItem().toString();
// selectChildId = id.substring(0, id.indexOf("--"));
postparameter = new ArrayList<NameValuePair>();
String parent_id = LoginPageActivity.id;
postparameter
.add(new BasicNameValuePair("parent_id", parent_id));
postparameter.add(new BasicNameValuePair("child_id",
selectChildId + ""));
String response = null;
try {
response = CustomHttpClient.executeHttpPost(URL2,
postparameter);
System.out.println("response:" + response);
if (response.trim().compareTo("success") == 0) {
Toast.makeText(getApplicationContext(),
"Child deleted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Failed to delete", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
You can use notifyDataSetChanged(); method to reload the adapter or display the changed data.
You should delete the item from you adapter list and then call spinner.notifyDataSetChanged() method to refresh you spinner
I have an SQLite table and in the certain activity I obtain all the names fom the table and populate a listview with these names.
Inside the listview listener, the user have can delete the selected item.
The problem is when I delete the item the app crashes.
Please take a look on my code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylocations);
tv_counter = (TextView) findViewById(R.id.counter);
tv_testCounter = (TextView) findViewById(R.id.testCounter);
lv = (ListView) findViewById(R.id.mylist);
mpoh = new MP_DB(this);
db = mpoh.getWritableDatabase();
cv = new ContentValues();
if (hasRecords()) {
Toast.makeText(getBaseContext(), getRowsNum()+" row(s)", Toast.LENGTH_SHORT).show();
get_MPNames();
arrayToArrayList();
setListView();
lv.setOnItemClickListener(listViewListener);
} else {
Toast.makeText(getBaseContext(), "NO RECORDS"+","+getRowsNum()+"rows", Toast.LENGTH_SHORT).show();
}
}
Here are the method to convert the array to arraylist, and the listview listener:
private void arrayToArrayList() {
int s = str.length;
al = new ArrayList<String>();
for (int i=0; i < s; i++) {
al.add(str[i]);
}
}
private int getRowsNum() {
return mpoh.getCurrentRowNumber();
}
OnItemClickListener listViewListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
pos = arg2;
showDialoge();
}
};
Here how I delete element from the DB and the ListView:
private void deleteMPfromListView(int pos) {
al.remove(pos);
adapter.notifyDataSetChanged();
Toast.makeText(getBaseContext(), al.size()+" rows left in list view", Toast.LENGTH_SHORT).show();
}
private void deleteMPFromDB(int pos) {
mpoh.deleteMP(pos);
Toast.makeText(getBaseContext(), getRowsNum()+" rows left in DB", Toast.LENGTH_SHORT).show();
}
private Boolean hasRecords() {
if (getRowsNum() == 0) {
return false;
} else {
return true;
}
}
private void setListView() {
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
android.R.id.text1, al);
lv.setAdapter(adapter);
}
private void get_MPNames() {
str = new String[getRowsNum()];
for (int i=0; i <= getRowsNum()-1; i++) {
str[i] = mpoh.getMP_Name(i+1);
} //tv_testCounter.setText(str[87]);
}
Removing from the database has nothing to do with removing them from the ListView. I have not code of your implementation but you may try something like this too dynamically add or remove items:
public class LVDemo extends ListActivity {
// handles the ListView data
ArrayAdapter<String> adapter;
// Items that are displayed
ArrayList<String> listItems=new ArrayList<String>();
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
listItems);
setListAdapter(adapter);
}
/**
* Remove item.
*/
public void removeItem(int index) {
listItems.remove(index);
adapter.notifyDataSetChanged();
}
}
In General: You change the the ArrayList containing the element and then notify the adapter for the ListView