Hi I am working with android listview.I want to create a dynamic list view in which user can add data dynamically to listview .So far its works fine. Now my problem is my contets are added at start position of listview .I want to add the added contents at last position of list view (like adding comments in facebook post). Is it possible to make ?? Please help me .Thanks in advance :)
MY activity class
public class MainActivity extends Activity {
private EditText etInput;
private Button btnAdd;
private ListView lvItem;
private ArrayList<String> itemArrey;
private ArrayAdapter<String> itemAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpView();
}
private void setUpView() {
// TODO Auto-generated method stub
etInput = (EditText)this.findViewById(R.id.editText_input);
btnAdd = (Button)this.findViewById(R.id.button_add);
lvItem = (ListView)this.findViewById(R.id.listView_items);
itemArrey = new ArrayList<String>();
itemArrey.clear();
itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,itemArrey);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addItemList();
}
});
etInput.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_ENTER) {
addItemList();
}
return true;
}
});
}
protected void addItemList() {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
if (isInputValid(etInput)) {
itemArrey.add(0,etInput.getText().toString());
etInput.setText("");
itemAdapter.notifyDataSetChanged();
}
}
protected boolean isInputValid(EditText etInput2) {
// TODO Auto-generatd method stub
if (etInput2.getText().toString().trim().length()<1) {
etInput2.setError("Please Enter Item");
return false;
} else {
return true;
}
}
}
Remove position from
itemArrey.add(0,etInput.getText().toString()); // Position=0
Try this way.
itemArrey.add(etInput.getText().toString());
that directly add your string at the end.
You are specifying position to add new element to. Just avoid using position and new item will be added at the end of list.
itemArrey.add( etInput.getText().toString() );
Further more, you might also like to scroll down to this newly added item. So you can use these in xml
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll"
or use setSelection() to do so like -
lvItem.setSelection(countOfItems-1);
Related
I have tried to use the examples and read those links that I think related to my project, but all of it have a different structure from mine. Hope anybody could help.
I have 3 spinners in my NewProfile.java class. In this class, user can input their profiles and also selecting the type of workout with the user interests. I have no problem saving the profile text input. But I have a problem to save the spinner value selected by the user. Following are my codes.
NewProfile.java
public class NewProfile extends Activity {
EditText profileName, profileDOB, profileSex, profileWeight, profileHeight;
Spinner workoutspinner, levelspinner, weightplan1, weightplan2,
weightplan3;
TextView display;
DBController controller = new DBController(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.newdata);
profileName = (EditText) findViewById(R.id.etName);
profileDOB = (EditText) findViewById(R.id.etDOB);
profileSex = (EditText) findViewById(R.id.etSex);
profileWeight = (EditText) findViewById(R.id.etWeight);
profileHeight = (EditText) findViewById(R.id.etHeight);
chooseWorkout();
chooseLevel();
chooseWeight1();
chooseWeight2();
chooseWeight3();
}
public void addNewProfile(View view) {
HashMap<String, String> queryValuesMap = new HashMap<String, String>();
queryValuesMap.put("profileName", profileName.getText().toString());
queryValuesMap.put("profileDOB", profileDOB.getText().toString());
queryValuesMap.put("profileSex", profileSex.getText().toString());
queryValuesMap.put("profileWeight", profileWeight.getText().toString());
queryValuesMap.put("profileHeight", profileHeight.getText().toString());
controller.insertProfile(queryValuesMap);
this.startingpointActivity(view);
}
private void startingpointActivity(View view) {
// TODO Auto-generated method stub
Intent objIntent = new Intent(getApplicationContext(),
StartingPoint.class);
startActivity(objIntent);
finish();
}
private void chooseWorkout() {
// TODO Auto-generated method stub
workoutspinner = (Spinner) findViewById(R.id.spinWorkout);
ArrayAdapter<CharSequence> workoutadapter = ArrayAdapter
.createFromResource(this, R.array.saWorkout,
android.R.layout.simple_spinner_item);
workoutadapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
workoutspinner.setAdapter(workoutadapter);
workoutspinner.setOnItemSelectedListener(new workoutOnClickListener());
}
private void chooseLevel() {
// TODO Auto-generated method stub
levelspinner = (Spinner) findViewById(R.id.spinLevel);
ArrayAdapter<CharSequence> leveladapter = ArrayAdapter
.createFromResource(this, R.array.saLevel,
android.R.layout.simple_spinner_item);
leveladapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
levelspinner.setAdapter(leveladapter);
levelspinner.setOnItemSelectedListener(new levelOnClickListener());
}
private void chooseWeight1() {
// TODO Auto-generated method stub
weightplan1 = (Spinner) findViewById(R.id.spinWeight);
ArrayAdapter<CharSequence> weightadapter1 = ArrayAdapter
.createFromResource(this, R.array.saWeight1,
android.R.layout.simple_spinner_item);
weightadapter1
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
weightplan1.setAdapter(weightadapter1);
}
private void chooseWeight2() {
// TODO Auto-generated method stub
weightplan2 = (Spinner) findViewById(R.id.spinWeight);
ArrayAdapter<CharSequence> weightadapter2 = ArrayAdapter
.createFromResource(this, R.array.saWeight2,
android.R.layout.simple_spinner_item);
weightadapter2
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
weightplan2.setAdapter(weightadapter2);
}
private void chooseWeight3() {
// TODO Auto-generated method stub
weightplan3 = (Spinner) findViewById(R.id.spinWeight);
ArrayAdapter<CharSequence> weightadapter3 = ArrayAdapter
.createFromResource(this, R.array.saWeight3,
android.R.layout.simple_spinner_item);
weightadapter3
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
weightplan3.setAdapter(weightadapter3);
}
public class workoutOnClickListener implements OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int pos,
long id) {
// TODO Auto-generated method stub
parent.getItemAtPosition(pos);
if (pos == 0) {
chooseLevel();
levelspinner.setClickable(true);
weightplan1.setClickable(true);
weightplan2.setClickable(true);
weightplan3.setClickable(true);
} else if (pos != 0){
levelspinner.setClickable(false);
weightplan1.setClickable(false);
weightplan2.setClickable(false);
weightplan3.setClickable(false);
Toast.makeText(getApplicationContext(),
"Wollaaaa! Only Program 1 is available for this moment. Sorry.. :)",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
public class levelOnClickListener implements OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int pos, long id) {
// TODO Auto-generated method stub
parent.getItemAtPosition(pos);
if (pos == 0) {
chooseWeight1();
} else if (pos == 1){
chooseWeight2();
} else if (pos == 2){
chooseWeight3();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
}
Do I need to change anything in my DBController in order to save these spinners? Please help. Thanks.
p/s Just to inform that the addNewProfile is a button that save all the information.
Okay, I'll do my best to answer as requested:
For a start, these are the key parts of setting and getting values from your spinners:
If you need to set the values in your spinners, you can use this.
mySpinner.setSelection(arrayAdapter.getPosition("Category 2")); //This assumes that "Category 2" exists in your spinner list.
To get the value from your spinner.
String Text = mySpinner.getSelectedItem().toString();
Here is a great discussion on what to DO with those values.
SharedPreferences example.
That pretty well explains how to save your preferences. It also should give you almost everything to answer your initial question.
The key part afterward is what to do with those prefs. This line shows how to set a string based on what it finds in the saved prefs, and if it finds nothing, will load "default".
This is helpful for when the user is running the app for the first time and prefs have never been set.
test_string=shared_preferences.getString("test_key", "Default");
Once those prefs have been set, and you want them to show in a different view, just add all this same sort of technique to the other view.
Hope that helps. For what it's worth, every last bit of this was taken from here, through various searches. Sometimes you need to look through a bunch of different things to find an answer if a simple solution is not in one place.
i am using java android .
i have a problem in my app and i need some code that can make my item has two lines of texts and one image .
please save me and help .
here is the code for what i tried please make sure that you can help and give your opinion and how i can solve it cause i stucked here.
the main activity
private void setUpView() {
// TODO Auto-generated method stub
etInput = (EditText)this.findViewById(R.id.editText_input);
Pinput = (EditText)this.findViewById(R.id.editText1);
btnAdd = (Button)this.findViewById(R.id.button_add);
lvItem = (ListView)this.findViewById(R.id.listView_items);
itemArrey = new ArrayList<String>();
itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,itemArrey);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addItemList();
}
});
etInput.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_ENTER){
addItemList();
}
return false ;
}
});
Pinput.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(keyCode== KeyEvent.KEYCODE_NUM) {
addItemList();
}
return;
}
});
}
protected void addItemList() {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
if (isInputValid(Pinput )) {
itemArrey.add(Pinput.getText().toString());
itemArrey.add(etInput.getText().toString());
Pinput.setText("");
etInput.setText("");
itemAdapter.notifyDataSetChanged();
} if (isInputValid(etInput )) {
itemArrey.add(Pinput.getText().toString());
itemArrey.add(etInput.getText().toString());
Pinput.setText("");
etInput.setText("");
itemAdapter.notifyDataSetChanged();
}
}
protected boolean isInputValid(EditText etInput2 ) {
// TODO Auto-generatd method stub
if (etInput2.getText().toString().trim().length()<1) {
return false;
} else {
return true;
}
}
}
If you want a custom view in your ListView I recommend doing one xml layout by yourself and replace android.R.layout.simple_list_item_1 in your Adapter call with the new created one.
This would be the easiest way but as I think that you might need more freedom to create/modify the content of the row, I strongly suggest to create your own Adapter extending from BaseAdapter. In the getView() method of the adapter you can easily inflate and set up the layout like you want for that row.
Okie... you tag android-listview and list view item. So I think you need list view with image and and Text.
For that you have to use Custom List View.
See this
May be this will help you. and not then pls make your que more clear. :)
My need is to
create a dynamic spinner on a button click
select the spinner values and set the values into an edit text field.
For this I have created a dynamic spinner programatically. Put that code inside button click listener. Its working fine upto here.
but the setOnitemSelectedListener of the dynamic spinner is not at all working.. there are no errors in the Logcat... please help me..
------------ These are the methods inside onCreate ------------
Spinner spnOutHospitalList = new Spinner(Referance.this);
// list button on click event
btnList = (Button) findViewById(R.id.btn_list);
btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// function to create spinner dynamically
createDynamicSpinner();
}
});
// Out Hospital List Spinner on item click listener
spnOutHospitalList.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long arg3) {
// TODO Auto-generated method stub
outHospitalName = hospitalNameListArray.get(position);
outHospital.setText(outHospitalName);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
------------ These are the functions outside onCreate but inside the Activity------------
// to create spinner dynamically
private void createDynamicSpinner() {
// TODO Auto-generated method stub
spnOutHospitalList.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
loadOutHospitalListSpinner();
spnOutHospitalList.performClick();
}
// to load out hospital/ clinic data into spinner
private void loadOutHospitalListSpinner() {
// TODO Auto-generated method stub
try {
if (getFirstRun()) {
sampleDB = dbAdapter.getDatabase();
setRunned();
}
else {
sampleDB = dbAdapter.getWritableDatabase();
}
Cursor c1 = sampleDB.rawQuery("select DISTINCT EPR_OUT_HOSPITAL from EMR_PT_REFERNCE",null);
System.out.println("count is " + c1.getCount());
if (c1 != null && c1.getCount() != 0) {
hospitalNameListArray.clear();
if (c1.moveToFirst()) {
do {
hospitalNameListArray.add(c1.getString(c1.getColumnIndex("EPR_OUT_HOSPITAL")));
} while (c1.moveToNext());
}
}
c1.close();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, hospitalNameListArray);
// dropdownlist
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnOutHospitalList.setAdapter(dataAdapter);
}
catch (Exception e) {
// TODO: handle exception
System.out.println("CAT LIST ERROR IS: " + e.getMessage());
}
}
Try this
Write setOnItemSelectedListener inside createDynamicSpinner
private void createDynamicSpinner() {
//Remove this line from top in your code and add here
Spinner spnOutHospitalList = new Spinner(Referance.this);
spnOutHospitalList.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
//Pass Spinner Object to this function to load data in it!
loadOutHospitalListSpinner(spnOutHospitalList);
spnOutHospitalList.performClick();
spnOutHospitalList.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long arg3) {
// TODO Auto-generated method stub
outHospitalName = hospitalNameListArray.get(position);
outHospital.setText(outHospitalName);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
Here is my code,
public class SecondScreenActivity extends Activity {
ListView foodJntListView;
ArrayList<Restaurent> restaurentData;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.second_screen);
restaurentData = getFoodJnt();
foodJntListView=(ListView)findViewById(R.id.listView_foodjnt);
foodJntListView.bringToFront();
// setting the adapter to the list
foodJntListView.setAdapter(new RestaurantBaseAdapter(this,restaurentData));
//setting the onclick listener,activity on clicking on an item of the
foodJntListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
String hotelname=restaurentData.get(position).toString();
//things to write
}
});
}
// get all the list of foodjoints
private ArrayList<Restaurent> getFoodJnt() {
// TODO Auto-generated method stub
ArrayList<Restaurent> results=new ArrayList<Restaurent>();
Restaurent restrnt=new Restaurent();
restrnt.setFoodJointname("Ashila");
restrnt.setCuisine("Biriyani,Moughlai");
restrnt.setAddress("Kolkata,E M Bypass");
restrnt.setOpenhours("10:00am-10:00pm");
results.add(restrnt);
restrnt=new Restaurent();
restrnt.setFoodJointname("Bhajohori Manna");
restrnt.setCuisine("Bengali,Chinese");
restrnt.setAddress("Kolkata,Esplanede");
restrnt.setOpenhours("10:00am-10:00pm");
results.add(restrnt);
restrnt=new Restaurent();
restrnt.setFoodJointname("Bar B Q");
restrnt.setCuisine("Bengali,Chinese,Thai");
restrnt.setAddress("Kolkata,Park Street");
restrnt.setOpenhours("10:00am-10:00pm");
results.add(restrnt);
return results;
}
public void makeAToast(String str) {
//yet to implement
Toast toast = Toast.makeText(this, str, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
I can able to show a customized listview with a bunch of textview on it as it's item but,I want to get the Name of the restauirants setOnItemClick on the List view.
e.g whenever I click Click on "Bar B Q","calcutta Food Court",it'll show me only "Bar B Q","calcutta Food Court" not other informations.
thnx in advance.Feel free to if u need anything.
"my application screen shot"
assume you've got method like getFoodJointname() in your Restaurent class, you can write the below in your onItemClick():
String hotelname = restaurentData.get(position).getFoodJointname();
makeAToast(hotelname);
this will work hopefully.
Restaurent rest= (Restaurent) foodJntListView.getSelectedItem();
public class CompanySearchActivity extends RathbonesActivity {
private CompanySearchAdapter mStockListAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.companysearch_layout);
final EditText keywordET = (EditText)findViewById(R.id.codeET);
final Button search = (Button)findViewById(R.id.button_stock_add);
final Activity a= CompanySearchActivity.this;
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String keyword = keywordET.getText().toString();
Log.i("keyword: ",keyword);
ArrayList codearr = getResults(keyword);
mStockListAdapter = new CompanySearchAdapter(a,codearr);
ListView listview = (ListView) findViewById(R.id.stocklist);
listview.setAdapter(mStockListAdapter);
listview.setOnItemClickListener(this);
listview.setOnItemLongClickListener(this);
}
});
}
The lines listview.setOnItemClickListener(this);
listview.setOnItemLongClickListener(this); are giving errors because of this keyword, i replaced it with 'a' too but it doesnt work. What can be the possible way to achieve this?
If you wish to use the parent activities onClick method your activity must implement OnItemClickListener and OnItemLongClickListener
public class CompanySearchActivity extends RathbonesActivity implements OnItemClickListener, OnItemLongClickListener
{
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
// TODO Auto-generated method stub
return false;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
// TODO Auto-generated method stub
}
}
Note the code "implements OnItemClickListener, OnItemLongClickListener"
This is vital for implementing it this way.
Then you can call:
listview.setOnItemClickListener(CompanySearchActivity.this);
listview.setOnItemLongClickListener(CompanySearchActivity.this);
The this keyword is a reference to the object that owns the currently executing method. In this case this refers to the anonymous View.OnClickListener object that you are defining. Try replacing this with CompanySearchActivity.this
your listview onClick definition should look like your search listener.
search.setOnClickListener(new View.OnClickListener() {
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String keyword = keywordET.getText().toString();
Log.i("keyword: ",keyword);
ArrayList codearr = getResults(keyword);
mStockListAdapter = new CompanySearchAdapter(a,codearr);
}
});
ListView listview = (ListView) findViewById(R.id.stocklist);
listview.setAdapter(mStockListAdapter);
listview.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
<do somthing when its clicked>
}
});
also ensure if you have multiple layouts that these view items (listview and search)
are in companysearch_layout.xml