listview is not visible at all - android

I'm facing problem with list view, there is a custom card layout view which should appear in the list view. This is main FirstActivity.java file including the adapter class, followed by the activity_first.xml, card_layout.xml, and a screenshot. My problem is that when I run this app, it installs successfully but the list view is not visible at all:
public class FirstActivity extends AppCompatActivity {
private Toolbar toolbar;
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
setupUIViews();
toolbarSettings();
setupListView();
}
catch (java.lang.NullPointerException exception) {
exception.printStackTrace();
}
}
private void setupUIViews () {
try {
toolbar = (Toolbar) findViewById(R.id.ToolbarMain);
listView = (ListView) findViewById(R.id.lv_main);
}
catch (java.lang.NullPointerException exception) {
exception.printStackTrace();
}
}
private void toolbarSettings() {
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("TimeTable");
}
private void setupListView () {
try {
String[] title = getResources().getStringArray(R.array.Main);
String[] description = getResources().getStringArray(R.array.Desc);
adapter adapter = new adapter(this, title, description);
listView.setAdapter(adapter);
} catch (java.lang.NullPointerException exception) {
exception.printStackTrace();
}
}
public class adapter extends BaseAdapter {
private Context mContext;
private LayoutInflater layoutInflater;
private TextView title, description;
private String[] titleArray;
private String[] descriptionArray;
private ImageView imageView;
public adapter(Context context, String[] titleArray, String[] descriptionArray) {
mContext = context;
titleArray = titleArray;
descriptionArray = descriptionArray;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
int length = 0;
try {
length = titleArray.length;
}
catch (java.lang.NullPointerException exception) {
exception.printStackTrace();
}
return length;
}
#Override
public Object getItem(int position) {
return titleArray[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null ) {
convertView = layoutInflater.inflate(R.layout.card_layout, null);
}
title = (TextView)convertView.findViewById(R.id.tv_heading);
description = (TextView)convertView.findViewById(R.id.tv_desc);
imageView = (ImageView)convertView.findViewById(R.id.iv_main);
title.setText(titleArray[position]);
description.setText(descriptionArray[position]);
if (titleArray[position].equalsIgnoreCase("TimeTable")) {
imageView.setImageResource(R.drawable.timetable);
}
else if (titleArray[position].equalsIgnoreCase("Subjects")) {
imageView.setImageResource(R.drawable.calender);
}
else if (titleArray[position].equalsIgnoreCase("Faculty")) {
imageView.setImageResource(R.drawable.contact);
}
else
imageView.setImageResource(R.drawable.settings);
return convertView;
}
}
}
Here is the first_activity.xml:
<?xml version="1.0" encoding="utf-8"?>
<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="wrap_content"
tools:context=".FirstActivity">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:background="#color/colorPrimary"
android:id="#+id/ToolbarMain">
</android.support.v7.widget.Toolbar>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_below="#+id/ToolbarMain"
android:divider="#null"
android:id="#+id/lv_main">
</ListView>
</RelativeLayout>
Here is the card_layout.xml file:-
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorAccent"
android:elevation="4dp">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="85dp"
android:layout_height="105dp"
android:layout_marginStart="10dp"
android:id="#+id/iv_main"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#id/iv_main"
android:textStyle="bold"
android:layout_marginBottom="5dp"
android:text="IshaanNagwani"
android:textSize="20sp"
android:id="#+id/tv_heading"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="IshaanNagwani"
android:textSize="16sp"
android:layout_below="#id/tv_heading"
android:layout_toEndOf="#id/iv_main"
android:id="#+id/tv_desc"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tv_desc"
android:layout_alignBottom="#id/iv_main"
android:layout_alignParentRight="true"
android:layout_marginTop="29sp"
android:text="IshaanNagwani"
android:textAlignment="center"
android:textSize="12sp"
android:id="#+id/tv_third"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
And finally, this is my strings.xml:-
<resources>
<string name="app_name">TimeTable</string>
<string-array name="Main">
<item>TimeTable</item>
<item>Subjects</item>
<item>Faculty</item>
<item>Resources</item>
</string-array>
<string-array name="Desc">
<item>desc_1</item>
<item>desc_2</item>
<item>desc_3</item>
<item>desc_4</item>
</string-array>
</resources>
I am new in android and this is my first post. I'm working with ListView. Apparently I am doing something quite wrong, but I cant figure out what is it.
This is the screenshot of the app, after it is gets completely installed:

In adapter constructor, some class variables's names are same with parameters's name. So, all manipulation will just be done for parameters, it makes size of this.titleArray will be zero then getCount() method always return 0 then no item appear on your activity. So you must use this to reference to the class variables. Modify your code as following:
public adapter(Context context, String[] titleArray, String[] descriptionArray) {
mContext = context;
this.titleArray = titleArray;
this.descriptionArray = descriptionArray;
layoutInflater = LayoutInflater.from(context);
}

Related

getView() not called even when getCount() has results

Sorry for my english, not my first language.
Im creating an app in Android and I have a issue:
I have a TabBar with 2 fragments (1 - ProductFragment and 2 - CartFragment), in second Fragment (CartFragment) I have a ListView and that ListView is initial null.
CartFragment Layout:
<FrameLayout 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:padding="15dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lancarvenda_carrinho_lvwresultado"
android:orientation="vertical" />
</LinearLayout>
</FrameLayout>
In ProductFragment I have a button with onclick, that onclick Intents another activity and in that activity I add values in my public Custom List:
public static List<PesquisarProdutoResponse> Carrinho = new ArrayList<>();
When I done with adding values that I need, I close that activity and return to TabBar and expects that ListView has been populated.
The method that populate my public list:
private void PesquisarProduto()
{
RequestQueue sQueue = Volley.newRequestQueue(getActivity());
String sEnderecoBase = "http://www.my-url";
StringRequest sRequest = new StringRequest(Request.Method.POST, sEnderecoBase, new Response.Listener<String>() {
#Override
public void onResponse(String response)
{
PesquisarProdutoResponse sResultado = new Gson().fromJson((String) response, PesquisarProdutoResponse.class);
if (sResultado.getCodigoRetorno() != 0)
{
//lastText = "Produto não encontrado";
//barcodeView.setStatusText("Produto não encontrado");
}
else
{
Variaveis.Carrinho.add(sResultado);
try {
List<PesquisarProdutoObjetoRetorno> sCarrinhoAuxiliar = new ArrayList<>();
for (int i = 0; i < Variaveis.Carrinho.size(); i++) {
PesquisarProdutoObjetoRetorno sItem = Variaveis.Carrinho.get(i).getDadosProduto();
sCarrinhoAuxiliar.add(sItem);
}
LancarVendaCarrinhoListViewAdapter sAdaptador = new LancarVendaCarrinhoListViewAdapter(getActivity(),
sCarrinhoAuxiliar);
fCarrinhoResultado.setAdapter(sAdaptador);
sAdaptador.notifyDataSetChanged();
Object oi = fCarrinhoResultado.getCount();
oi.toString();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
byte[] sBytesResposta = error.networkResponse.data;
String sTexto = new String(sBytesResposta);
Mensagem.ExibirAlert(getActivity(), String.valueOf(error.networkResponse.statusCode));
}
})
{
#Override
public Map<String, String> getHeaders() throws AuthFailureError
{
Map<String, String> sHeaders = new HashMap<>();
sHeaders.put("Authorization", "Bearer " + Variaveis.ApiToken);
return sHeaders;
}
#Override
public byte[] getBody() throws AuthFailureError
{
return new Gson().toJson(sCorpoBusca).getBytes();
}
#Override
public String getBodyContentType()
{
return "application/json";
}
};
sQueue.add(sRequest);
}
ListView Adapter:
public class LancarVendaCarrinhoListViewAdapter extends BaseAdapter
{
private Context mContext;
//private LayoutInflater mInflater;
private List<PesquisarProdutoObjetoRetorno> mDataSource;
public LancarVendaCarrinhoListViewAdapter(Context context, List<PesquisarProdutoObjetoRetorno> items)
{
mContext = context;
mDataSource = items;
}
#Override
public int getCount() {
return mDataSource.size();
}
#Override
public Object getItem(int position) {
return mDataSource.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
try
{
LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View sView = mInflater.inflate(R.layout.activity_lancarvenda_carrinho_list_view_item, parent, false);
PesquisarProdutoObjetoRetorno sItem = (PesquisarProdutoObjetoRetorno) getItem(position);
TextView descricao = (TextView)sView.findViewById(R.id.lancarvenda_carrinho_item_txtdescricao);
descricao.setText(sItem.getDescricao());
TextView preco = (TextView)sView.findViewById(R.id.lancarvenda_carrinho_item_txvpreco);
preco.setText(String.valueOf(sItem.getPreco()));
EditText quantidade = (EditText)sView.findViewById(R.id.lancarvenda_carrinho_item_etquantidade);
quantidade.setText("1");
return sView;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
}
My layout of row:
<RelativeLayout 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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/lancarvenda_carrinho_item_imvFoto"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_gravity="center_horizontal"
android:background="#drawable/circulo_foto2"
app:border_color="#898989"
app:border_width="2dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginLeft="10dp">
<TextView
android:id="#+id/lancarvenda_carrinho_item_txtdescricao"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Relogio"
android:textSize="20dp"
android:textStyle="bold"
android:layout_marginRight="8dp"
android:lines="2"
android:minLines="2"
android:singleLine="false"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/lancarvenda_carrinho_item_txvpreco"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="8dp"
android:text="R$ 399,89"
android:textColor="#1ba39c"
android:textSize="20dp"
android:layout_marginRight="70dp"/>
<EditText
android:id="#+id/lancarvenda_carrinho_item_etquantidade"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:backgroundTint="#9a9b9c"
android:hint="0"
android:textColor="#2a2d2e"
android:layout_marginRight="8dp"/>
</RelativeLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
In debug mode, when code pass in getCount in Adapter, I have size more than 1 and my list still not show! Even if I close TabBar and reopen and set adapter (with values) on onCreate method.
What can I do to my ListView show?
EDIT
I inflate listview on onCreate:
super.onCreate(savedInstanceState);
LayoutInflater sInflater = getActivity().getLayoutInflater();
View sView = sInflater.inflate(R.layout.fragment_lancarvenda_carrinho, null);
fCarrinhoResultado = (ListView) sView.findViewById(R.id.lancarvenda_carrinho_lvwresultado);
Try making your list a member of the class instead of a local variable
private void PesquisarProduto()
{
RequestQueue sQueue = Volley.newRequestQueue(getActivity());
String sEnderecoBase = "http://www.my-url";
StringRequest sRequest = new StringRequest(Request.Method.POST, sEnderecoBase, new Response.Listener<String>() {
// Make cart list a private data member so it doesn't loose scope //
List<PesquisarProdutoObjetoRetorno> sCarrinhoAuxiliar;
#Override
public void onResponse(String response)
{
PesquisarProdutoResponse sResultado = new Gson().fromJson((String) response, PesquisarProdutoResponse.class);
if (sResultado.getCodigoRetorno() != 0)
{
//lastText = "Produto não encontrado";
//barcodeView.setStatusText("Produto não encontrado");
}
else
{
Variaveis.Carrinho.add(sResultado);
try {
sCarrinhoAuxiliar = new ArrayList<>();
...
}
...
}
...
}
...
}
...
}
Declare your List sCarrinhoAuxiliar and adapter sAdaptador as global.
Update your OnCreateView() as below:
// Global
List<PesquisarProdutoObjetoRetorno> sCarrinhoAuxiliar;
LancarVendaCarrinhoListViewAdapter sAdaptador;
.........................
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
....................
........................
sCarrinhoAuxiliar = new ArrayList<>();
sAdaptador = new LancarVendaCarrinhoListViewAdapter(getActivity(), sCarrinhoAuxiliar);
fCarrinhoResultado.setAdapter(sAdaptador);
.......................
...............
}
Update your onResponse() method as below:
#Override
public void onResponse(String response) {
.....................
..........................
try {
// Clear old data
sCarrinhoAuxiliar.clear();
for (int i = 0; i < Variaveis.Carrinho.size(); i++) {
PesquisarProdutoObjetoRetorno sItem = Variaveis.Carrinho.get(i).getDadosProduto();
sCarrinhoAuxiliar.add(sItem);
}
// Update list
sAdaptador.notifyDataSetChanged();
.............
....................
}
catch (Exception e) {
e.printStackTrace();
}
}
Hope this will help~
I got help from another forum and I was able to solve my problem:
I override two methods: OnCreate (inflate and receive view) and OnCreateView (find the product and put on listview), I eliminate method OnCreate and put everything on OnCreateView!
That solve my problem!
Thanks to everybody!

Implement RecyclerView with CardView and GridView

Im trying to implement a RecyclingView that contains a CardView which contains a GridView. Not getting any errors just nothing is showing. Just a white screen when I try to run the app.
public class MainActivity extends AppCompatActivity {
TextView mWeatherTemp, mWeatherDescript;
RecyclerView.Adapter adapter;
Context context;
GridView gridView;
String[] mTime = {
"1:00",
"2:00",
"3:00",
"4:00",
"5:00",
"6:00",
"7:00",
"8:00",
"9:00",
"10:00",
"11:00",
};
String[] mDegreeTemp = {
"8°",
"12°",
"43°",
"100°",
"32°",
"12°",
"58°",
"39°",
"29°",
"86°",
"70°",
};
int[] imageId = {
R.mipmap.ic_launcher
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
Toolbar mToolbar = (Toolbar) findViewById(R.id.mMainToolbar);
setSupportActionBar(mToolbar);
mToolbar.setBackgroundColor(ContextCompat.getColor(this, R.color.weather_cool));
mWeatherTemp = (TextView) findViewById(R.id.tvWeatherTemp);
mWeatherDescript = (TextView) findViewById(R.id.tvWeatherText);
Typeface robotDisplay3 = Typeface.createFromAsset(getApplicationContext().getAssets(),
"font/Roboto-Regular.ttf");
mWeatherTemp.setTypeface(robotDisplay3);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.mHourlyRV);
HourlyGridAdapter adapter = new HourlyGridAdapter(getApplicationContext(), mTime, mDegreeTemp, imageId);
gridView = (GridView) findViewById(R.id.hourlyGridView);
gridView.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.settings, menu);
return super.onCreateOptionsMenu(menu);
}
}
public class HourlyGridAdapter extends BaseAdapter {
private Context mContext;
private String[] mTime;
private String[] mDegreeTemp;
private final int[] imageId;
public HourlyGridAdapter(Context context, String[] mTime, String[] mDegreeTemp, int[] imageId) {
mContext = context;
this.imageId = imageId;
this.mDegreeTemp = mDegreeTemp;
this.mTime = mTime;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.hourly_single, null, false);
holder = new ViewHolder();
holder.timeText = (TextView) convertView.findViewById(R.id.timePlaceHolder);
holder.degreeText = (TextView) convertView.findViewById(R.id.degreePlaceHolder);
holder.weatherImage = (ImageView) convertView.findViewById(R.id.weatherIconHolder);
holder.timeText.setText(mTime[position]);
holder.degreeText.setText(mDegreeTemp[position]);
holder.weatherImage.setImageResource(imageId[position]);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
static class ViewHolder {
TextView timeText, degreeText;
ImageView weatherImage;
}
}
Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
card_view:cardCornerRadius="6dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/tvDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TODAY" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/forecast_card_divider" />
<GridView
android:id="#+id/hourlyGridView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:horizontalSpacing="12dp"
android:numColumns="4"
android:verticalSpacing="12dp" />
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/timePlaceHolder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/timePlaceHolderText"
android:layout_gravity="center"/>
<ImageView
android:id="#+id/weatherIconHolder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/ic_launcher"
android:layout_gravity="center"/>
<TextView
android:id="#+id/degreePlaceHolder"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="12°"
android:layout_gravity="center"/>
</LinearLayout>
Im not even sure if having a GridView inside a CardView all inside a recycled view is possible. Any help trying to create this would be creately appreicated.
PS. I know im not calling recyclerView thats declared as that doesnt work and does crash the app and the GridView is null. Not really sure what to do here. Not sure if I need to create an adapter for the recyclerview as all the textViews and ImageView is in the grid not the cardview.
You are initializing and setting adapter for gridview which is inside each item of recyclerview not in recycler adapter but in activity. Consider removing all gridview-related code to recyclerview's adapter.

Android ListAdapter :NullPointerException exception

This code works in basic Activity, but it doesn't in Tabbed activity.
I want to use the ListView with custom view.
Common code:
list_row.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textView2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/textView3" />
</LinearLayout>
It is my simple data class, I want to show it:
String nev;
String szakma;
public String getNev() {
return nev;
}
public void setNev(String nev) {
this.nev = nev;
}
public String getSzakma() {
return szakma;
}
public void setSzakma(String szakma) {
this.szakma = szakma;
}
public Adat(String nev, String szakma) {
this.nev = nev;
this.szakma = szakma;
}
And my custom ListAdapter:
public class EgyeniAdapter extends BaseAdapter {
Context context;
ArrayList<Adat> adatok;
public EgyeniAdapter(Context context, ArrayList<Adat> adatok) {
this.context = context;
this.adatok = adatok;
}
#Override
public int getCount() {
return adatok.size();
}
#Override
public Object getItem(int position) {
return adatok.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_row,null); // itt rendelem hozza a saját viewet
if (convertView != null)
{
TextView Cim = (TextView) convertView.findViewById(R.id.textView2);
TextView Alcim = (TextView) convertView.findViewById(R.id.textView3);
Adat adatom = adatok.get(position);
Cim.setText(adatom.getNev());
Alcim.setText(adatom.getSzakma());
}
return convertView;
}
}
And it is my MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
...
betolt();
}
private void betolt()
{
ArrayList<Adat> adataim = new ArrayList<>();
adataim.add(new Adat("Title","Subtitle"));
adataim.add(new Adat("Title2","Subtitle2"));
final ListView myList= (ListView) findViewById(R.id.listView);
EgyeniAdapter egyeniAdapter = new EgyeniAdapter(this,adataim);
myList.setAdapter(egyeniAdapter);
}
This works, but when I want use it in another application in Tabbed activity, it throws:
NullPointerException: Attempt to invoke virtual method 'void
android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a
null object reference
What is the problem?
My fragment code:
<FrameLayout 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"
tools:context="com.example.mpet8.englishtest.Tesztek">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment"
android:id="#+id/tesztek_label"
/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tesztek_listView"
android:layout_gravity="left|top" />
</FrameLayout>
I call my method in onStart method:
#Override
protected void onStart() {
super.onStart();
betolt();
}
in betolt() you are looking for a ListView with the id R.id.listView (final ListView myList= (ListView) findViewById(R.id.listView);) but in your fragmentlayout it has the id android:id="#+id/tesztek_listView"

Android - Listview not showing the last item

My Problem is the last item in the listview is not displaying even though it has been added to the adapter and as well as in the list as i can see the number of items in the adapter is ok. Is it the problem with the layout? this is my layout
<?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:background="#drawable/golive_bg"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:id="#+id/Room"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus android:layout_width="wrap_content" />
</EditText>
<Button
android:id="#+id/Search1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Search" />
<ImageButton
android:id="#+id/CreateRoomimageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/closed_doorplus" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ListView
android:id="#+id/listRooms"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fastScrollEnabled="true"
android:transcriptMode="alwaysScroll">
</ListView>
</LinearLayout>
</LinearLayout>
This is my class activity
public class chatRoomsListActivity extends Activity implements OnScrollListener {
private static String Password;
private ListView lv;
private static Collection<HostedRoom> rooms;
private static ArrayList<String> Roomlist = new ArrayList<String>();
private static Handler mHandler = new Handler();
private Button SearchButton;
private ImageButton CreateButton;
private EditText EditTextSearch;
private String Search;
private String RoomName;
private static ChatRoomListAdapter adapter;
private static String Nickname="";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_rooms);
SearchButton=(Button)findViewById(R.id.Search1);
CreateButton=(ImageButton)findViewById(R.id.CreateRoomimageButton);
lv = (ListView) findViewById(R.id.listRooms);
adapter = new ChatRoomListAdapter(getApplicationContext(),
R.layout.chat_rooms_wrapper);
lv.setAdapter(adapter);
//ScrollView.measureChildWithMargins();
try {
populate_RoomList();
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
addListenerOnButton();
/*
arrayAdapter = new ArrayAdapter<String>(
this,android.R.layout.simple_list_item_1,Roomlist);
lv.setAdapter(arrayAdapter);
*/
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parnet,
android.view.View view,
int position, long id) {
setRoomName(ChatRoomListAdapter.getItemName(position));
showOptionDialog();
}
});
addListenerOnButton();
}
public void addListenerOnButton() {
final Context context = this;
CreateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
createRoomDialog();
}
});
SearchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
EditTextSearch=(EditText) findViewById(R.id.Room);
Search=EditTextSearch.getText().toString();
//Search=Search.concat("*");
try {
// populate_RoomList();
getSearchlist();
// updateList();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void getSearchlist() throws XMPPException{
Roomlist.clear();
adapter.clear();
ChatRoomListAdapter.getChatRoom().clear();
rooms=getHostedRooms(MyService.getConnection(),"conference."+
MyService.getDomain());
System.out.println("in getsearch");
for (HostedRoom h : rooms)
{
System.out.println(h.getName().toString()+" contain " +Search);
if(h.getName().toString().contains(Search)){
System.out.println("roomlist= " +h.getJid().toString());
Roomlist.add(h.getName());
System.out.println("ChatRooms.IsRoomPassProtected(h.getName())==
"+ChatRooms.IsRoomPassProtected(h.getName()));
if(ChatRooms.IsRoomPassProtected(h.getName())==true){
adapter.add(new ChatRoom(h.getName(),true));
}
else if(ChatRooms.IsRoomPassProtected(h.getName())==false){
adapter.add(new ChatRoom(h.getName(),false));
}
}
}
System.out.println("Adapter count="+adapter.getCount());
}
private void populate_RoomList() throws XMPPException {
//chatRoomsList.getRooms();"
Roomlist.clear();
adapter.clear();
//rooms.clear();
ChatRoomListAdapter.getChatRoom().clear();
rooms=getHostedRooms(MyService.getConnection(),"conference."+
MyService.getDomain());
//System.out.println(rooms.iterator().next().getName());
for (HostedRoom h : rooms)
{
System.out.println("roomlist= " +h.getName().toString());
Roomlist.add(h.getName());
System.out.println("ChatRooms.IsRoomPassProtected(h.getName())==
"+ChatRooms.IsRoomPassProtected(h.getName()));
if(ChatRooms.IsRoomPassProtected(h.getName())==true){
adapter.add(new ChatRoom(h.getName(),true));
}
else if(ChatRooms.IsRoomPassProtected(h.getName())==false){
adapter.add(new ChatRoom(h.getName(),false));
}
}
System.out.println("Adapter count="+adapter.getCount());
}
public void setRoomName(String roomName) {
RoomName = roomName;
}
public static Collection<HostedRoom> getHostedRooms(Connection connection, String serviceName)
throws XMPPException {
List<HostedRoom> answer = new ArrayList<HostedRoom>();
ServiceDiscoveryManager discoManager = new
ServiceDiscoveryManager(connection);
DiscoverItems items = discoManager.discoverItems(serviceName);
for (Iterator<DiscoverItems.Item> it = items.getItems(); it.hasNext();) {
answer.add(new HostedRoom(it.next()));
}
return answer;
}
}
And this is my custom adapter
public class ChatRoomListAdapter extends ArrayAdapter<ChatRoom> {
private TextView name;
private static List<ChatRoom> ChatRoom = new ArrayList<ChatRoom>();
private LinearLayout wrapper;
private ImageView lock;
public ChatRoomListAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public static List<ChatRoom> getChatRoom() {
return ChatRoom;
}
public static void setChatRoom(List<ChatRoom> chatRoom) {
ChatRoom = chatRoom;
}
public ChatRoom getItem(int index) {
return ChatRoomListAdapter.ChatRoom.get(index);
}
public static String getItemName(int index) {
return ChatRoomListAdapter.ChatRoom.get(index).name;
}
public static void setfriends(List<Friends> friends) {
FriendListAdapter.setFriends(friends);
}
public void add(ChatRoom object) {
System.out.println("IN Chat room list adapter "+" addded");
ChatRoomListAdapter.ChatRoom.add(object);
super.add(object);
}
public void remove(ChatRoom object) {
ChatRoom.remove(object);
super.remove(object);
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = (LayoutInflater)
this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.chat_rooms_wrapper, parent, false);
}
wrapper = (LinearLayout) row.findViewById(R.id.C_R_wrapper);
name = (TextView) row.findViewById(R.id.C_R_RoomName);
lock=(ImageView)row.findViewById(R.id.C_R_Lock);
try {
Log.d("Chat room adapter", "heere");
ChatRoom CR= getItem(position);
System.out.println("name= "+CR.name);
name.setText(CR.name);
if(CR.lock==true)
{
lock.setImageResource(R.drawable.lock_lock_icon);
}else{
lock.setImageResource(R.drawable.lock_unlock_icon);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return row;
}
public Bitmap decodeToBitmap(byte[] decodedByte) {
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}
}
Thanks in advance.
Add this line to your Viewpager
android:layout_marginBottom="?attr/actionBarSize"
because the size you don't have at the bottom is exactly the size taken by your Toolbar
Example with RecyclerView
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view_trips"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:layout_marginBottom="?attr/actionBarSize"/>
Example with Viewpager
<android.support.v4.view.ViewPager
android:id="#+id/viewpager_trip_history"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="?attr/actionBarSize" />
Try this you can solve your problem with this:
You just need to change your xml file as below:
<?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:background="#drawable/golive_bg"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="6" >
<EditText
android:id="#+id/Room"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:layout_weight="4">
<requestFocus android:layout_width="wrap_content" />
</EditText>
<Button
android:id="#+id/Search1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Search"
android:layout_weight="1" />
<ImageButton
android:id="#+id/CreateRoomimageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/closed_doorplus"
android:layout_weight="1" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/listRooms"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fastScrollEnabled="true"
android:transcriptMode="alwaysScroll">
</ListView>
</RelativeLayout>
</LinearLayout>
You can get the last item inside getView of the Adapter and change it layout params height by setLayoutParams. But the minus is you have to correct other items height because the height will change when scroll the list up/down
Maybe its very simple. Try to set the layout_height of your listview in the xml file to wrap_content.
android:layout_height="wrap_content"
Try to set the second LinearLayout holding the Listview to match_parent height... It seems like your LinearLayout is growing with the ListView (wrap_content) out of your screen space

get data from Intent Activity and button activated in ListView

Hi thanks for reading this! Please help me.
I am trying to create a restaurant app which the display 3 buttons in the menu then click the food button which display the list of food, then customer can choose the food they want to order then send back the order back to first page. I read a lot of the article and some say use the listview.setItemsCanFocus(true) but I having problem to understand it to implement it. and some say the button listener inside the getView but when I implement my program just hang. Please help me. Thank you.
my menu :
here is my food(second) page
I am having problems:
to transfer the data back from the food.class back to my main class which is
restaurant.class
After I add the button in the list the food is not clickable(the whole row of food).
my main class(restaurant)
public class SesameRestaurant extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void foodMenu(View v){
startActivity(new Intent(SesameRestaurant.this,Food.class));
//setContentView(R.layout.foods);
}
public void drinkMenu(View v){startActivity(new Intent(SesameRestaurant.this,Drink.class));}
public void billMenu(View v){}
}
my second class (food.class)
package com.restaurant.sesame;
public class Food extends ListActivity {
private LayoutInflater mInflater;
private Vector<RowData> data;
RowData rd;
static final String[] title = new String[] {
"Cow Rib steak",
"Thai Prawn Fried Rice",
"Christmas Sensation Delight",
"Salmon Steak" };
static final String[] detail = new String[] {
"1h 37m Shipping: $10.00",
"1h 39m Shipping: Free",
"58m 6s Shipping: $10.00",
"59m 30s Shipping: $10.95" };
private Integer [] imgid = { R.drawable.food1, R.drawable.food2, R.drawable.food3, R.drawable.food4 };
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.foods);
mInflater = (LayoutInflater) getSystemService(
Activity.LAYOUT_INFLATER_SERVICE);
data = new Vector<RowData>();
for(int i=0;i<title.length;i++){
try {
rd = new RowData(i,title[i],detail[i]);
} catch (ParseException e) {
e.printStackTrace();
}
data.add(rd);
}
CustomAdapter adapter = new CustomAdapter(this, R.layout.list, R.id.title, data);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
}
public void onListItemClick(ListView parent, View v, int position, long id) {
Log.w("my app", "Click list Item!!!");
Toast.makeText(getApplicationContext(), "You have selected "+(position+1)+"th item", Toast.LENGTH_SHORT).show();
}
public void orderClick(View v){
}
private class RowData {
protected int mId;
protected String mTitle;
protected String mDetail;
RowData(int id,String title,String detail)
{
mId=id;
mTitle = title;
mDetail=detail;
}
#Override
public String toString() {
return mId+" "+mTitle+" "+mDetail;
}
}
private class CustomAdapter extends ArrayAdapter<RowData> {
public CustomAdapter(Context context, int resource, int textViewResourceId, List<RowData> objects) {
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
TextView title = null;
TextView detail = null;
ImageView i11=null;
RowData rowData= getItem(position);
if(null == convertView){
convertView = mInflater.inflate(R.layout.list, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
title = holder.gettitle();
title.setText(rowData.mTitle);
detail = holder.getdetail();
detail.setText(rowData.mDetail);
i11=holder.getImage();
i11.setImageResource(imgid[rowData.mId]);
return convertView;
}
private class ViewHolder {
private View mRow;
private TextView title = null;
private TextView detail = null;
private ImageView i11=null;
public ViewHolder(View row) {
mRow = row;
}
public TextView gettitle() {
if(null == title){
title = (TextView) mRow.findViewById(R.id.title);
}
return title;
}
public TextView getdetail() {
if(null == detail){
detail = (TextView) mRow.findViewById(R.id.detail);
}
return detail;
}
public ImageView getImage() {
if(null == i11){
i11 = (ImageView) mRow.findViewById(R.id.img);
}
return i11;
}
}
}
public void backClick(View v){
finish();
}
}
my food menu interface foods.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:layout_height="wrap_content"
android:text="Back"
android:onClick="backClick"
android:layout_width="fill_parent">
</Button>
my list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView android:id="#+id/img"
android:scaleType="centerCrop"
android:layout_width="100dp"
android:layout_height="100dp"/>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:paddingLeft="10dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="fill_parent"
android:id="#+id/title"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textColor="#ffffff"
android:textSize="16sp" />
<TextView
android:layout_width="fill_parent"
android:id="#+id/detail"
android:textColor="#ffffff"
android:layout_height="wrap_content"/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Quantity :"
android:textColor="#ffffff" />
<EditText
android:id="#+id/quantityInput"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:layout_toRightOf="#id/quantity"
android:hint="1-10"
android:paddingLeft="10dp"
android:textSize="12dp" />
<Button
android:id="#+id/order"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="120dp"
android:layout_toRightOf="#id/quantity"
android:onClick="orderClick"
android:text="Order"
android:textSize="12dp" />
</RelativeLayout>
</LinearLayout>
I'm at school now so I don't have time to get a you a code snippet at all but you are going to need to use startActivityForResult() instead of just startActivity(). This will allow you to send information back to your main app upon completion of the your food activity.
Respond if you need me to find a snippet for you and I'll write one up quick once I get home in about an hour.

Categories

Resources