Print lines in Listview using an adapter - android

I need to output data from lines cm1 and cm2 in a ListView, every time when I press the button. Line should be shown in various TextView.
Code TEST.java:
public String cm1;
public String cm2;
public class TEST extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyList = (ListView) this.findViewById(R.id.listStrings);
setListAdapter();
// button
Button setup = (Button) this.findViewById(R.id.send);
setup.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
cm1 = "cm1text";
cm2 = "cm2text";
//xxxx
}
});
}
// adapter
private void setListAdapter() {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.row //idknow what im must writehere to set cm1 string to cm1text tv
List.setAdapter(adapter);
}
Code TEST.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/listStrings"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1" />
<Button
android:id="#+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send" />
</LinearLayout>
Code row.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/cm1tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/cm2tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Should look ListView after 2 clicks:
cm1
cm2
cm1
cm2

Maybe what you should/can do is have this;
String cm = cm1 + "\n" + cm2
Which should output;
cm1
cm2
Then you change the xml to just have one textview and the adapter code as follows;
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> aa = new ArrayAdapter<String>(this, R.layout.row, R.id.textViewCM, listItems);
yourListView.setAdapter(aa);
Then, whenever you press the button;
// ...code to initialise/change cm
listItems.add(cm);
aa.notifyDataSetChanged(); // notifies listView to update it's view
That should do what you're after unless you've got to have the two individual textViews, in which case, you'll need to write a custom adapter, I've done a bit of a tutorial on my website if you follow that link.

Related

Android onItemClick method not working for item of ids other than 0

I have a problem with onItemClick method in android.
I know other people have encountered such problems, found some references to their questions on SO, read about the answers provided and some other articles on the internet but it didn't help. Things seem a bit different in my case.
I have a listview of some objects for which I want to show details when they're clicked. But Awkwardly the listener is working fine for only the first object of the listview. The app keeps aborting when I click on other elements of the listview. I can't figure out what's going on.
As I was using the id to retrieve the object I tried changing the id by the position, which didn't work either.
Here is the code of the onCreate method in my activity (DrinkCategoryActivity)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drink_category);
ArrayAdapter<Drink> listAdapter = new ArrayAdapter<>(
this, android.R.layout.simple_list_item_1, Drink.drinks
);
ListView listDrinks = (ListView) findViewById(R.id.list_drinks);
listDrinks.setAdapter(listAdapter);
AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> listDrinks,
View itemView, int position, long id) {
Intent intent = new Intent(DrinkCategoryActivity.this, DrinkActivity.class);
intent.putExtra(DrinkActivity.EXTRA_DRINKID, (int) id);
startActivity(intent);
}
};
listDrinks.setOnItemClickListener(itemClickListener);
}
My DrinkActivity (the one that should show me the details of each Drink object when clicked in the listview) onCreate method code is shown below
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drink);
int drinkId = (int) getIntent().getExtras().get(EXTRA_DRINKID);
Drink drinkItem = Drink.drinks[drinkId];
ImageView image = (ImageView) findViewById(R.id.drink_image);
image.setImageResource(drinkItem.getImageResourceId());
TextView drink_name = (TextView) findViewById(R.id.drink_name);
drink_name.setText(drinkItem.getName());
TextView drink_description = (TextView) findViewById(R.id.drink_description);
drink_description.setText(drinkItem.getDescription());
TextView drink_price = (TextView) findViewById(R.id.drink_price);
String price = ""+drinkItem.getPrice();
drink_price.setText(price);
}
I don't know whether there is something wrong with the xml files so here they are :
activity_drink_category.xml goes below
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".activities.DrinkCategoryActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
layout="#layout/customer_screen_toolbar_layout"/>
<ListView
android:layout_marginTop="10dp"
android:id="#+id/list_drinks"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</androidx.drawerlayout.widget.DrawerLayout>
And activity_drink.xml goes here
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".activities.DrinkActivity">
<include
layout="#layout/customer_screen_toolbar_layout"/>
<ImageView
android:id="#+id/drink_image"
android:layout_width="190dp"
android:layout_height="190dp" />
<TextView
android:id="#+id/drink_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/drink_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/drink_price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:background="#EB8E13"
android:textColor="#color/white" />
</LinearLayout>
Any help will be valuable. Thanks in advance
You need to pass "Position" instead of "id" in Intent. As you describe above its works fine for the first position. Then you need to Use position
intent.putExtra(DrinkActivity.EXTRA_DRINKID, (int) position);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drink_category);
ArrayAdapter<Drink> listAdapter = new ArrayAdapter<>(
this, android.R.layout.simple_list_item_1, Drink.drinks
);
ListView listDrinks = (ListView) findViewById(R.id.list_drinks);
listDrinks.setAdapter(listAdapter);
AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> listDrinks,
View itemView, int position, long id) {
Intent intent = new Intent(DrinkCategoryActivity.this, DrinkActivity.class);
intent.putExtra(DrinkActivity.EXTRA_DRINKID, (int) position);
startActivity(intent);
}
};
listDrinks.setOnItemClickListener(itemClickListener);
}

align listview from right to left

I'm developing with android studio.
I have a ListView that the elements in it are aligned from left to right and I want to align them from right to left, how can I do so?
the java class is:
public class ProductList extends ListActivity {
ArrayList<String> list = new ArrayList<String>(Arrays.asList("במבה אוסם", "בשר טחון", "קוקה קולה שישייה", "קפה עלית", "שמיר", "מילקי","רבעיית דניאלה"));
ArrayAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pop_productlist);
Button btnDel = (Button) findViewById(R.id.btnDel);
adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_multiple_choice, list);
/** Defining a click event listener for the button "Delete" */
View.OnClickListener listenerDel = new View.OnClickListener() {
#Override
public void onClick(View v) {
/** Getting the checked items from the listview */
SparseBooleanArray checkedItemPositions = getListView().getCheckedItemPositions();
int itemCount = getListView().getCount();
for(int i=itemCount-1; i >= 0; i--){
if(checkedItemPositions.get(i)){
adapter.remove(list.get(i));
}
}
checkedItemPositions.clear();
adapter.notifyDataSetChanged();
}
};
/** Setting the event listener for the delete button */
btnDel.setOnClickListener(listenerDel);
/** Setting the adapter to the ListView */
setListAdapter(adapter);
}
public void StartCalck(View view){
Intent intent = new Intent(ProductList.this, SplitBuying.class);
startActivity(intent);
}
}
and the layout is:
<LinearLayout
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:orientation="vertical">
<ListView
android:id="#android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:choiceMode="multipleChoice"
android:layout_below="#+id/ChooseStore">
</ListView>
</LinearLayout>
Thank you !
Use RecyclerView instead of ListView.
LinearLayoutManager(Context context, int orientation, boolean reverseLayout)
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right" ><br>
<TextView
android:id="#+id/textView_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"/><br>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:layout_toLeftOf="#+id/textView_name"/>
</RelativeLayout>
Manifest.xml
<application
....
android:supportsRtl="true"
...
</application>
you should use custom layout like
myTextView.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:gravity="right"
android:background="#bdbdbd"/>
pass this layout to adapter like
ArrayAdapter adapter = new ArrayAdapter(this,R.layout.nameOfLayout, list);

I converted a fragment to a dialog and now text colors have changed

This is my first app. I had been setting a preference in an activity (with a fragment), but I want to move the fragment to a DialogPreference. It migrated okay, except my text colors have gone weird. See picture. The text should just be black, not white and gray. Any idea what I got wrong?
(Sorry, I know this is pretty sloppy code)
How it looks now:
My xml...
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/relLay_dialog_semester_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<TextView
android:id="#+id/select_semester_prompt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/select_semester_prompt" />
<LinearLayout
android:id="#+id/linLayGradeSum"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/select_semester_prompt"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp" >
<Spinner
android:id="#+id/semester_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="3"
android:hint="#string/hint_editSemester" />
<Spinner
android:id="#+id/year_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4" />
</LinearLayout>
<TextView
android:id="#+id/active_semesters_str"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/linLayGradeSum"
android:layout_below="#+id/linLayGradeSum"
android:text="#string/active_semester_str"
android:textAppearance="?android:attr/textAppearanceMedium" />
<LinearLayout
android:id="#+id/active_semesters_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/active_semesters_str"
android:layout_below="#+id/active_semesters_str"
android:layout_marginTop="10dp"
android:orientation="vertical" >
</LinearLayout>
</RelativeLayout>
My extended DialogPreference class
public class SemesterDialogPreference extends DialogPreference {
SharedPreferences settings;
public static int YEAR_DEFAULT_VALUE = Activity_AddCourse.thisYear - Activity_AddCourse.baseYear;
public static int SEASON_DEFAULT_VALUE = Semester.getDefaultSemester().getSeasonInt();
public static int SEMESTER_DEFAULT_ID = 1;
String semester_id_key;
DBAdapter db;
// this is where I do everything view-related
#Override
public void onBindDialogView(View view){
settings = getSharedPreferences();
int curSemesterId = settings.getInt(semester_id_key, 1);
db = new DBAdapter(this.getContext().getApplicationContext());
db.open();
Semester curSemester = db.getSemester(curSemesterId);
db.close();
ArrayList<String> years = new ArrayList<String>();
for (int i = Activity_AddCourse.baseYear; i <= Activity_AddCourse.maxYear; i++)
{
years.add(Integer.toString(i));
}
ArrayAdapter<String> adapter_year = new ArrayAdapter<String>(this.getContext().getApplicationContext(),
android.R.layout.simple_spinner_item, years);
Spinner spinYear = (Spinner)view.findViewById(R.id.year_spinner);
adapter_year.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinYear.setAdapter(adapter_year);
spinYear.setSelection(curSemester.getYear() - Activity_AddCourse.baseYear);
Spinner spinner = (Spinner) view.findViewById(R.id.semester_spinner);
ArrayAdapter<CharSequence> adapter_spinner = ArrayAdapter.createFromResource(this.getContext().getApplicationContext(),
R.array.semester_spinner, android.R.layout.simple_spinner_item);
adapter_spinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter_spinner);
spinner.setSelection(Semester.seasonStringToInt(curSemester.getSeason()));
db = new DBAdapter(this.getContext().getApplicationContext());
db.open();
Semester[] s = db.getAllSemesters();
db.close();
String activeSem;
LinearLayout semesterList = (LinearLayout) view.findViewById(R.id.active_semesters_list);
if(s != null){
for(int i = 0; i < s.length; i++){
activeSem = s[i].getSemesterString();
TextView tv = (TextView) new TextView(this.getContext().getApplicationContext());
tv.setText(activeSem);
semesterList.addView(tv);
System.out.println(s[i].getSemesterString());
}
}
super.onBindDialogView(view);
}
public SemesterDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
setDialogLayoutResource(R.layout.dialog_set_semester);
}
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
persistBoolean(positiveResult);
}
}
UPDATE:
The DialogPreference pops up from my settings activity, as shown below.
public class SettingsActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
}
Also, I was able to get the spinner text to black by making my own xml layouts for them, just as Huy Tran suggested. However, I had to make one for each the spinner_item and the spinner_dropdown_item. See below.
ArrayAdapter<String> adapter_year = new ArrayAdapter<String>(this.getContext().getApplicationContext(),
R.layout.my_spinner_item, years);
Spinner spinYear = (Spinner)view.findViewById(R.id.year_spinner);
adapter_year.setDropDownViewResource(R.layout.my_spinner_dropdown_item);
Why did I have to do this? I don't know. Also, dropdown items are each now about 50% taller. I copied exactly from source code into my own xml and it still renders differently. Very weird.
Create a layout like below and use that layout in setDropDownViewResource instead of android.R.layout.simple_spinner_dropdown_item.
Create my_spinner_dropdown_item.xml in res/layout:
EDITED:
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
style="?android:attr/spinnerDropDownItemStyle"
android:singleLine="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:textColor="#color/black"
/>
my_spinner_item
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
style="?android:attr/spinnerItemStyle"
android:singleLine="true"
android:textColor="#android:color/transparent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee" />
Try using margin to change the size of each item.
And then in your SemesterDialogPreference:
setDropDownViewResource(R.layout.my_spinner_dropdown_item);

Issue with ListView adapter

When I comment out the code for "nameAdapter = ..." or "numAdapter = ..." and leave the other one uncommented it will display the data in the listview fine. So it is able to display both separately, however, when I leave both uncommented it will only display the data involved with numAdapter. Probably a simple mistake but I can't figure out where I went wrong.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player);
lv = (ListView) findViewById(R.id.listView);
new Logo().execute();
new statistics().execute();
nameAdapter = new ArrayAdapter<String>(this, R.layout.simple_list_item_1, R.id.stat_name,statName);
numAdapter = new ArrayAdapter<String>(this, R.layout.simple_list_item_1, R.id.stat_number,statNum);
}
private class statistics extends AsyncTask<String, Void, String> {
//final ListView listview = (ListView) findViewById(R.id.listView);
/*String[] values = new String[]{ "Ball Control", "Crossing", "Curve",
"Dribbling", "Finishing", "Free Kick Accuracy", "Heading Accuracy", "Long Passing",
"Long Shots", "Marking", "Penalties", "Short Passing", "Shot Power", "Sliding Tackle",
"Standing Tackle", "Volleys"};*/
//String[] stats = new String[16];
#Override
protected String doInBackground(String... arg) {
Document document;
try {
document = Jsoup.connect(url).get();
num = document.select("div#stats-base p");
statNum.clear();
for (Element element : num) {
statNum.add(element.ownText());
}
name = document.select("div#stats-base span");
statName.clear();
for (Element element : name) {
statName.add(element.ownText());
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
lv.setAdapter(nameAdapter);
lv.setAdapter(numAdapter);
}
}
player.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/playerPic"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_below="#+id/playerPic"
android:layout_centerHorizontal="true"
android:layout_marginTop="104dp"/>
</RelativeLayout>
simple_list_item_1.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView android:id="#+id/stat_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold"/>
<TextView
android:id="#+id/stat_number"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold"
android:layout_below="#id/stat_name"/>
</LinearLayout>
I think there's no mystery in that behavior. The last adapter you set to lv is the one that survives.
If what you're looking for is to add both statName and statNum, I'd set one of them and afterwards use .addAll(...) on the other. For instance:
lv = lv.setAdapter(nameAdapter);
lv.addAll(statNum);
nameAdapter.notifyDataSetChanged();
Don't forget the last line to let your ListView render the new data.

displaying user input from edit text to list view

I have problem with adding 2 numbers in list view. This is my row with 2 text view (for each numer). textView2 ignore
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="0"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView3"
android:gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" - "
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
When user add number it will display in list view. That second number needs to be 11 - that number that user inserted. It's all working but I dont know how to display that second number.
public class MainActivity extends Activity {
ArrayAdapter<String> m_adapter;
ArrayList<String> m_listItems = new ArrayList<String>();
Button bt;
EditText et;
TextView tv;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Inflate the menu; this adds items to the action bar if it is present.
bt = (Button) findViewById(R.id.button1);
et = (EditText) findViewById(R.id.editText1);
tv = (TextView) findViewById(R.id.textView1);
lv = (ListView) findViewById(R.id.lista);
m_adapter = new ArrayAdapter<String>(this,R.layout.row, R.id.textView1);
lv.setAdapter(m_adapter);
//final String input = et.getText().toString();
bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String input = et.getText().toString();
if(null!=input&&input.length()>0){
String maxpunti = "11";
int a = Integer.parseInt(maxpunti);
int b = Integer.parseInt(input);
int c = a-b;
String input2 = String.valueOf(c);
m_adapter.add(input);
m_adapter.add(input2);
m_adapter.notifyDataSetChanged();
}
}
});
}
}
The default implementation of ArrayAdapter<String> binds a single Stringvalue to a a single textfield. Since you have several views for each listitem or "row" in your listview ( you need to implement/extend your own ArrayAdapter and override the getView method.
Them you can set the values for any number of custom views that you may have in your list item layout.
Look at a simple example and also it might be a good idea to look som docs on how listviews/adpters work in android since they are very central.

Categories

Resources