I'm trying to put two images in a listView using a ArrayList, but when I run the project, just one image appear (the truck one), but the star one didn't appear. The Android Studio didn't show me any error.
Someone can look at my code and point me, what am I doing wrong?
ListaDistribuidoresActivity.java
package com.pedido.meu.telas_meu_pedido;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class ListaDistribuidoresActivity extends AppCompatActivity {
ItemAdapter adapter;
ArrayList<Integer> idImages;
ArrayList<String> nameList;
ArrayList<Integer> starImage;
int ids[]={R.mipmap.ic_distribuidor};
String names[]={"DISTRIBUIDOR"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_distribuidores);
ListView listViewDistribuidores = findViewById(R.id.txtListViewDistribuidores);
idImages = new ArrayList<>();
idImages = getList();
starImage = new ArrayList<>();
starImage = getListStar();
nameList = new ArrayList<>();
nameList = getNameList();
ItemAdapter adapter = new ItemAdapter(ListaDistribuidoresActivity.this, idImages,nameList, starImage);
listViewDistribuidores.setAdapter(adapter);
listViewDistribuidores.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Toast.makeText(ListaDistribuidoresActivity.this, "Distribuidor " + nameList.get(position) + "selecionado", Toast.LENGTH_SHORT).show();
}
});
}
private ArrayList<Integer> getListStar()
{
starImage = new ArrayList<>();
starImage.add(R.mipmap.ic_star_round);
return starImage;
}
private ArrayList<String> getNameList()
{
nameList = new ArrayList<>();
nameList.add("DISTRIBUIDOR 1");
nameList.add("DISTRIBUIDOR 2");
nameList.add("DISTRIBUIDOR 3");
nameList.add("DISTRIBUIDOR 4");
return nameList;
}
private ArrayList<Integer> getList()
{
idImages = new ArrayList<>();
idImages.add(R.mipmap.ic_distribuidor);
idImages.add(R.mipmap.ic_distribuidor);
idImages.add(R.mipmap.ic_distribuidor);
idImages.add(R.mipmap.ic_distribuidor);
return idImages;
}
}
ItemAdapter.java
package com.pedido.meu.telas_meu_pedido;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class ItemAdapter extends BaseAdapter
{
private Context context;
private ArrayList<Integer> listaId;
private ArrayList<String> listaNome;
private ArrayList<Integer> listaStar;
public ItemAdapter(Context context, ArrayList<Integer> listaId, ArrayList<String> listaNome, ArrayList<Integer> listaStar)
{
this.context = context;
this.listaId = listaId;
this.listaNome=listaNome;
this.listaStar=listaStar;
}
public ItemAdapter(ListaProdutosActivity listaProdutosActivity, ArrayList<Integer> idImages, ArrayList<String> nameList)
{
this.context=listaProdutosActivity;
this.listaId=idImages;
this.listaNome=nameList;
}
#Override
public int getCount()
{
return listaNome.size();
}
#Override
public Object getItem(int position)
{
return listaNome.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
convertView = View.inflate(context, R.layout.list_item_produtos, null);
}
ImageView img = convertView.findViewById(R.id.imgListItemProduto);
TextView tv = convertView.findViewById(R.id.txtListItemProduto);
img.setImageResource(listaId.get(position));
tv.setText(listaNome.get(position));
return convertView;
}
}
Imagem.java
package com.pedido.meu.telas_meu_pedido;
public class Imagem
{
private int imageId;
private String imageName;
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getImageName() {
return imageName;
}
public void setImageName(String imageName) {
this.imageName = imageName;
}
}
activity_lista_distribuidores.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.pedido.meu.telas_meu_pedido.ListaDistribuidoresActivity"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#mipmap/ic_distribuidor"
android:layout_gravity="center"
android:layout_marginTop="30dp"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/txtTitleListaDistribuidores"
android:gravity="center"
android:textColor="#color/colorPrimary"
android:textStyle="bold"
android:textSize="14pt"
android:layout_marginTop="15dp"
android:layout_marginBottom="20dp"
/>
<ListView
android:id="#+id/txtListViewDistribuidores"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
list_item_distribuidor.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android" >
<ImageView
android:id="#+id/imgListaProdutos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#mipmap/ic_acai"
android:layout_marginLeft="8dp"
/>
<TextView
android:id="#+id/txtDistribuidor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="#+id/imgListaProdutos"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#mipmap/ic_star_round"
android:layout_alignParentTop="#+id/imgListaProdutos"
android:layout_marginLeft="30dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Update your list_item_distribuidor.xml with below one
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android" >
<ImageView
android:id="#+id/imgListaProdutos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#mipmap/ic_acai"
android:layout_marginLeft="8dp"
/>
<TextView
android:id="#+id/txtDistribuidor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="#+id/imgListaProdutos"
/>
<ImageView android:id="#+id/imgListaStar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#mipmap/ic_star_round"
android:layout_alignParentTop="#+id/imgListaProdutos"
android:layout_marginLeft="30dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
and your ItemAdapter.java class with below one
package com.pedido.meu.telas_meu_pedido;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class ItemAdapter extends BaseAdapter
{
private Context context;
private ArrayList<Integer> listaId;
private ArrayList<String> listaNome;
private ArrayList<Integer> listaStar;
public ItemAdapter(Context context, ArrayList<Integer> listaId, ArrayList<String> listaNome, ArrayList<Integer> listaStar)
{
this.context = context;
this.listaId = listaId;
this.listaNome=listaNome;
this.listaStar=listaStar;
}
public ItemAdapter(ListaProdutosActivity listaProdutosActivity, ArrayList<Integer> idImages, ArrayList<String> nameList)
{
this.context=listaProdutosActivity;
this.listaId=idImages;
this.listaNome=nameList;
}
#Override
public int getCount()
{
return listaNome.size();
}
#Override
public Object getItem(int position)
{
return listaNome.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
convertView = View.inflate(context, R.layout.list_item_produtos, null);
}
ImageView img = convertView.findViewById(R.id.imgListaProdutos);
TextView tv = convertView.findViewById(R.id.txtListItemProduto);
ImageView imgStar = convertView.findViewById(R.id.imgListaStar);
img.setImageResource(listaId.get(position));
tv.setText(listaNome.get(position));
imgStar.setImageResource(listaStar.get(0));
return convertView;
}
}
you were not setting the image,
let me know if it worked
Use this library :
implementation 'com.squareup.picasso:picasso:2.5.2'
and do this in adapter:
ImageView img = convertView.findViewById(R.id.imgListItemProduto);
Picasso.with(context).load(listaId.get(position)).into(img);
There is an issue in your XML and adapter. First, add the id to the XML of that second image, star image I suppose.
list_item_distribuidor.xml
<ImageView
android:id="#+id/imgListStars"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#mipmap/ic_star_round"
android:layout_alignParentTop="#+id/imgListaProdutos"
android:layout_marginLeft="30dp"
/>
Then in ItemAdapter.java initialize it by it's ID and set it's value from the list.Just the way you're doing with your other (truck) image.
ImageView imgStar = convertView.findViewById(R.id.imgListStars);
imgStar.setImageResource(listaStar.get(position));
Full Functional Code
ListaDistribuidoresActivity.java
package com.pedido.meu.telas_meu_pedido.controller;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import com.pedido.meu.telas_meu_pedido.R;
import com.pedido.meu.telas_meu_pedido.adapter.ItemAdapter;
import java.util.ArrayList;
public class ListaDistribuidoresActivity extends AppCompatActivity {
ItemAdapter adapter;
ArrayList<Integer> idImages;
ArrayList<String> nameList;
ArrayList<Integer> starImage;
int ids[]={R.mipmap.ic_distribuidor};
String names[]={"DISTRIBUIDOR"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_distribuidores);
ListView listViewDistribuidores = findViewById(R.id.txtListViewDistribuidores);
Spinner spinner = findViewById(R.id.spinnerCategoria);
ArrayAdapter<CharSequence> adapterSpinner = ArrayAdapter.createFromResource(ListaDistribuidoresActivity.this, R.array.category_array, android.R.layout.simple_spinner_dropdown_item);
adapterSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapterSpinner);
idImages = new ArrayList<>();
idImages = getList();
starImage = new ArrayList<>();
starImage = getListStar();
nameList = new ArrayList<>();
nameList = getNameList();
ItemAdapter adapter = new ItemAdapter(ListaDistribuidoresActivity.this, idImages,nameList, starImage);
listViewDistribuidores.setAdapter(adapter);
listViewDistribuidores.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Toast.makeText(ListaDistribuidoresActivity.this, "Distribuidor " + nameList.get(position) + "selecionado", Toast.LENGTH_SHORT).show();
}
});
}
private ArrayList<Integer> getListStar()
{
starImage = new ArrayList<>();
starImage.add(R.mipmap.ic_star_round);
return starImage;
}
private ArrayList<String> getNameList()
{
nameList = new ArrayList<>();
nameList.add("DISTRIBUIDOR 1");
nameList.add("DISTRIBUIDOR 2");
nameList.add("DISTRIBUIDOR 3");
nameList.add("DISTRIBUIDOR 4");
return nameList;
}
private ArrayList<Integer> getList()
{
idImages = new ArrayList<>();
idImages.add(R.mipmap.ic_distribuidor);
idImages.add(R.mipmap.ic_distribuidor);
idImages.add(R.mipmap.ic_distribuidor);
idImages.add(R.mipmap.ic_distribuidor);
return idImages;
}
}
Imagem.java
package com.pedido.meu.telas_meu_pedido.modelo;
public class Imagem
{
private int imageId;
private String imageName;
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getImageName() {
return imageName;
}
public void setImageName(String imageName) {
this.imageName = imageName;
}
}
ItemAdapter.java
package com.pedido.meu.telas_meu_pedido.adapter;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.pedido.meu.telas_meu_pedido.controller.ListaProdutosActivity;
import com.pedido.meu.telas_meu_pedido.R;
import java.util.ArrayList;
public class ItemAdapter extends BaseAdapter {
private Context context;
private ArrayList<Integer> listaId;
private ArrayList<String> listaNome;
private ArrayList<Integer> listaStar;
public ItemAdapter(Context context, ArrayList<Integer> listaId, ArrayList<String> listaNome, ArrayList<Integer> listaStar) {
this.context = context;
this.listaId = listaId;
this.listaNome = listaNome;
this.listaStar = listaStar;
}
public ItemAdapter(ListaProdutosActivity listaProdutosActivity, ArrayList<Integer> idImages, ArrayList<String> nameList) {
this.context = listaProdutosActivity;
this.listaId = idImages;
this.listaNome = nameList;
}
#Override
public int getCount() {
return listaNome.size();
}
#Override
public Object getItem(int position) {
return listaNome.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
int view = 0;
if (convertView == null)
{
if(view == R.layout.list_item_produtos)
{
convertView = View.inflate(context, R.layout.list_item_produtos, null);
ImageView imgProducts = convertView.findViewById(R.id.imgListItemProduto);
TextView textViewProducts = convertView.findViewById(R.id.txtListItemProduto);
imgProducts.setImageResource(listaId.get(position));
textViewProducts.setText(listaNome.get(position));
}
else
{
convertView = View.inflate(context, R.layout.list_item_distribuidor, null);
ImageView imgDistributor = convertView.findViewById(R.id.imgStarDistributor);
TextView textDistribuidor = convertView.findViewById(R.id.txtDistribuidor);
imgDistributor.setImageResource(listaStar.get(0));
textDistribuidor.setText(listaNome.get(position));
}
}
return convertView;
}
}
activity_lista_distribuidores.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.pedido.meu.telas_meu_pedido.controller.ListaDistribuidoresActivity"
>
<ImageView
android:id="#+id/imgTitleListDistributor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#mipmap/ic_distribuidor"
android:layout_gravity="center"
android:layout_marginTop="30dp"
android:contentDescription="#string/txtTitleListaDistribuidores"
/>
<TextView
android:id="#+id/txtTitleDistributor"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/txtTitleListaDistribuidores"
android:gravity="center"
android:textColor="#color/colorPrimary"
android:textStyle="bold"
android:textSize="14pt"
android:layout_marginTop="15dp"
android:layout_marginBottom="20dp"
/>
<Spinner
android:id="#+id/spinnerCategoria"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="15dp"
/>
<ListView
android:id="#+id/txtListViewDistribuidores"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
list_item_distribuidor.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<ImageView
android:id="#+id/imgListaDistribuidor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#mipmap/ic_distribuidor"
android:layout_marginLeft="15dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
/>
<TextView
android:id="#+id/txtDistribuidor"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginStart="122dp"
android:layout_marginLeft="122dp"
android:layout_marginRight="-150dp"
android:textStyle="bold"/>
<ImageView
android:id="#+id/imgStarDistributor"
android:layout_width="20dp"
android:layout_height="20dp"
android:background="#mipmap/ic_star_round"
android:layout_marginLeft="295dp"
android:layout_marginTop="35dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="4.2"
android:layout_marginLeft="320dp"
android:layout_marginTop="35dp"
android:textStyle="bold"
/>
</RelativeLayout>
Related
I have text in the model. Must carry adapter. public int cid = -1; public String category_name; I want to transfer text only to the adapter. When I transfer some errors occur.I have tried to transfer from text model many times in adapter but I am not getting text i am new devloper How to fix this error
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.kannada.newspaper.india.R;
import com.kannada.newspaper.india.activities.MainActivitym;
import com.kannada.newspaper.india.model.Category;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class GalleryAdapter extends BaseAdapter {
private Context context;
private List<Category> mensWears;
public GalleryAdapter(Context context, List<Category> mensWears) {
this.context = context;
this.mensWears = mensWears;
}
#Override
public int getCount() {
return mensWears.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i,View view,ViewGroup viewGroup) {
final Category mensWear = mensWears.get(i);
if (view == null) {
final LayoutInflater layoutInflater = LayoutInflater.from(context);
view = layoutInflater.inflate(R.layout.custom_gallery_layout, null);
}
//For text
// TextView prdId = view.findViewById(R.id.name);
// prdId.setText(prdId.toString());
// //For images
// final ImageView imageView = view.findViewById(R.id.name);
// if(!TextUtils.isEmpty(mensWear.getItemName())){
//
//// Picasso.with(context).load(imageUrlFromServer+mensWear.category_image())
//// .into(imageView);
return view;
}
}
this model
public class Category implements Serializable {
public int cid = -1;
public String category_name;
public String category_image;
public String recipes_count;
public Category(String name, String profession, int photo) {
}
public String getItemName() {
return this.category_name;
}
public String category_image() {
return this.category_image;
}
}
layout
<com.kannada.newspaper.india.utils.SquareFrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/ll_main"
android:padding="#dimen/nav_header_vertical_spacing"
android:orientation="vertical">
<ImageView
android:background="#drawable/bg_google"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/imageView"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<LinearLayout
android:layout_width="100dp"
android:layout_height="100dp"
android:alpha="1"
android:background="#drawable/bg_roundiconimg"
android:gravity="center"
android:orientation="vertical">
<!-- <ImageView-->
<!-- android:id="#+id/photo"-->
<!-- android:layout_width="60dp"-->
<!-- android:layout_height="60dp"-->
<!-- android:layout_gravity="center" />-->
</LinearLayout>
<TextView
android:id="#+id/name"
android:layout_width="347dp"
android:layout_height="263dp"
android:layout_marginTop="#dimen/margin10"
android:fontFamily="#font/sfprodisplayregular"
android:text="Facebook"
android:textColor="#color/colorWhite"
android:textSize="#dimen/primeryText" />
</LinearLayout>
</com.kannada.newspaper.india.utils.SquareFrameLayout>
You are doing wrong you have to get the value from models not from the textview as in your sample you are doing below
TextView prdId = view.findViewById(R.id.name);
prdId.setText(prdId.toString());
you need to get the value from the model like below
prdId.setText(mensWears.get(i).getItemName());
I m trying to add the value from textview dynamically to listview.For that I have created another layout to take the values from user. but I'm not able to do that. I have tried many things. Kindly help.. Here is my code.
package com.example.chetan.assignment;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// String[] name= {"Apple","Banana","Mango","PineApple"};
//String[] price = {"Rs.40","Rs.60","Rs.70","Rs.80"};
List<String> names = new ArrayList<String>();
//String[] names = {"names"};
List<String> prices = new ArrayList<String>();
//String[] prices = {"prices"};
String name = getIntent().getStringExtra("name");
String price = getIntent().getStringExtra("price");
if(count==0) {
names.add(0, "name");
prices.add(0, "price");
}
if (count>0) {
names.add(count, name);
prices.add(count,price);
}
count++;
ListAdapter MyAdapter = new MyAdapter(names, prices, this);
ListView theList = (ListView) findViewById(R.id.listView);
theList.setAdapter(MyAdapter);
}
public void buttonClick(View view) {
Intent i = new Intent(this, Addlayout.class);
startActivity(i);
}
}
package com.example.chetan.assignment;
package com.example.chetan.assignment;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;
class MyAdapter extends BaseAdapter {
String[] name;
String[] price;
Context context;
private static LayoutInflater myInflater = null;
public MyAdapter(String[] name, String[] price, Context context) {
this.name = name;
this.price = price;
this.context = context;
myInflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return name.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public class Holder
{
TextView nametext;
TextView pricetext;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder myholder = new Holder();
View myViews = myInflater.inflate(R.layout.myview,parent,false);
myholder.nametext= (TextView) myViews.findViewById(R.id.textView);
myholder.pricetext= (TextView) myViews.findViewById(R.id.textView2);
myholder.nametext.setText(name[position]);
myholder.pricetext.setText(price[position]);
return myViews;
}
}
package com.example.chetan.assignment;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Addlayout extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addlayout);
}
public void Onclickbutton(View view){
EditText nametext = (EditText)findViewById(R.id.editText);
EditText pricetext = (EditText)findViewById(R.id.editText2);
String namedata = nametext.getText().toString();
String pricedata = pricetext.getText().toString();
Intent intent = new Intent(this,MainActivity.class);
intent.putExtra("name",namedata);
intent.putExtra("price",pricedata);
startActivity(intent);
}
}
Here you can do something like this:
Instead of simple listview I have used RecyclerView as it has better performance.
//First create a Data class for name and price
public class Data implements Serializable {
private String name,price;
public Data(){}
public Data(String name,String price){
this.name = name;
this.price = price;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//your Addlayout class
public class Addlayout extends AppCompatActivity {
List<Data> dataList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addlayout);
}
public void Onclickbutton(View view){
EditText nameText = (EditText)findViewById(R.id.editText);
EditText priceText = (EditText)findViewById(R.id.editText2);
String nameData = nameText.getText().toString();
String priceData = priceText.getText().toString();
Data data = new Data(nameData, priceData);
dataList.add(data);
Intent intent = new Intent(this,MainActivity.class);
intent.putExtra("List", (Serializable) dataList);
startActivity(intent);
}
}
//add layout xml
//change layout according to you
<?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:id="#+id/activity_addlayout"
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"
tools:context="com.example.mmc.testproject.Addlayout">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:hint="name"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginStart="13dp"
android:id="#+id/editText" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:hint="price"
android:layout_below="#+id/editText"
android:layout_alignEnd="#+id/editText"
android:layout_marginTop="18dp"
android:id="#+id/editText2" />
<Button
android:text="Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText2"
android:layout_alignStart="#+id/editText2"
android:layout_marginStart="43dp"
android:layout_marginTop="36dp"
android:onClick="Onclickbutton"
android:id="#+id/button" />
</RelativeLayout>
//Then your Listview Adapter
public class ListViewAdaptor extends RecyclerView.Adapter<ListViewAdaptor.MyViewHolder> {
private List<Data> mDataList;
public class MyViewHolder extends RecyclerView.ViewHolder{
public TextView name,price;
public MyViewHolder(View view){
super(view);
name = (TextView) view.findViewById(R.id.name);
price= (TextView) view.findViewById(R.id.price);
}
}
public ListViewAdaptor(List<Data> dataList){
this.mDataList = dataList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_view_item, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Data data = mDataList.get(position);
holder.name.setText(data.getName());
holder.price.setText(data.getPrice());
}
#Override
public int getItemCount() {
return mDataList.size();
}
}
//your Listview layout to show name and price
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/name"
android:text="name"
android:gravity="center"
android:textSize="26sp"
android:layout_weight="1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/price"
android:text="price"
android:gravity="center"
android:textSize="26sp"
android:layout_weight="1"/>
</LinearLayout>
//And finally the main Activity
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private ListViewAdaptor mAdapter;
private List<Data> mDataList;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
Intent i = getIntent();
mDataList = (List<Data>) i.getSerializableExtra("List");
Log.e(TAG,"Datalist size : "+mDataList.size());
mAdapter = new ListViewAdaptor(mDataList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setAdapter(mAdapter);
}
}
//and main 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:id="#+id/activity_main"
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"
tools:context="com.example.mmc.testproject.MainActivity">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recycler_view">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
Hope it helps!!!
every one,
I am a beginning learner on android system ,
I create a small app that could get specific data , like foreign exchange rate from bank website ,
this app uses Jsoup , ListView , BaseAdapter etc...
finally , the only problem is the listView has no any display ,
could any one tell me , how to fix it.
Thanks.
Category.java
public class Category
{
String bank_name;
String page_url;
Category(String bank_name,String url)
{
this.bank_name=bank_name;
this.page_url=url;
}
#Override
public String toString()
{
return bank_name;
}
}
MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.content.*;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends Activity
{
ArrayList<Category> items;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
items=new ArrayList<Category>();
items.add(new Category("台灣銀行","http://rate.bot.com.tw/Pages/Static/UIP003.zh-TW.htm"));
ArrayAdapter<Category> adapter = new ArrayAdapter<Category>(this , android.R.layout.simple_list_item_1 ,items);
ListView lv = (ListView)findViewById(R.id.lv);
lv.setAdapter(adapter);
lv.setOnItemClickListener(itemClick);
}
OnItemClickListener itemClick = new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> av , View v , int position , long id)
{
Category category = items.get(position);
Intent intent = new Intent();
intent.setClass(MainActivity.this , RateActivity.class );
intent.putExtra("bank_name", category.bank_name);
intent.putExtra("page_url" , category.page_url);
startActivity(intent);
}
};
RateBean.java
public class RateBean
{
private String currency;
private String cashBuy;
private String cashSold;
private String spotBuy;
private String spotSold;
public RateBean()
{
currency = "";
cashBuy = "";
cashSold = "";
spotBuy = "";
spotSold = "";
}
public RateBean(String [] strArr)
{
this.currency=strArr[0];
this.cashBuy=strArr[1];
this.cashSold=strArr[2];
this.spotBuy=strArr[3];
this.spotSold=strArr[4];
}
public RateBean(String currency , String cashBuy , String cashSold , String spotBuy ,String spotSold)
{
setCurrency(currency);
setCashBuy(cashBuy);
setCashSold(cashSold);
setSpotBuy(spotBuy);
setSpotSold(spotSold);
}
//Currency setter and getter
public void setCurrency(String currency)
{
this.currency = currency ;
}
public String getCurrency()
{
return currency;
}
//Cash buy setter and getter
public void setCashBuy(String cashBuy)
{
this.cashBuy = cashBuy;
}
public String getCashBuy()
{
return cashBuy;
}
//Cash sold setter and getter
public void setCashSold(String cashSold)
{
this.cashSold = cashSold;
}
public String getCashSold()
{
return cashSold;
}
//Spot buy setter and getter
public void setSpotBuy(String spotBuy)
{
this.spotBuy = spotBuy;
}
public String getSpotBuy()
{
return spotBuy;
}
//Spot sold setter and getter
public void setSpotSold(String spotSold)
{
this.spotSold = spotSold;
}
public String getSpotSold()
{
return spotSold;
}
}
RateActivity.java
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
public class RateActivity extends ListActivity
{
Context context ;
ArrayList<RateBean> rateBean_item;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rate_show);
TextView updateTime = (TextView)findViewById(R.id.updateTime_textView);
Intent intent = getIntent();
String category = intent.getStringExtra("bank_name");
String page_url = intent.getStringExtra("page_url");
setTitle(category);
context=this;
ConnectThread thread = new ConnectThread(context , rateBean_item , page_url , updateTime);
thread.start();
}
public class ConnectThread extends Thread
{
Context context;
ArrayList<RateBean> rateBean_item;
String page_url ;
TextView updateTime;
RateAdapter adapter;
RateBean rateBean;
int i =0;
public ConnectThread(Context context , ArrayList<RateBean> rateBean_item , String page_url , TextView updateTime )
{
this.context=context;
this.rateBean_item=rateBean_item;
this.page_url=page_url;
this.updateTime=updateTime;
}
#Override
public void run()
{
try
{
String currency="";
String cashBuy="";
String cashSold="";
String spotBuy="";
String spotSold="";
Document doc = Jsoup.connect(page_url).get();
rateBean_item = new ArrayList<>();
String temp=doc.select("td[style=width:326px;text-align:left;vertical-align:top;color:#0000FF;font-size:11pt;font-weight:bold;]").text();
String time=temp.substring(12);
updateTime.setText("匯率更新時間:\n" + time);
for( Element title:doc.select("td.titleLeft"))
{
currency=title.text();
if( i < doc.select("td.decimal").size())
{
cashBuy=doc.select("td.decimal").eq(i++).text();
cashSold=doc.select("td.decimal").eq(i++).text();
spotBuy=doc.select("td.decimal").eq(i++).text();
spotSold=doc.select("td.decimal").eq(i++).text();
rateBean = new RateBean( a , b , c ,d , e );
rateBean_item.add(rateBean);
}
}
adapter = new RateAdapter(context , rateBean_item);
setListAdapter(adapter);
adapter.notifyDataSetChanged();
}
catch( Exception exception )
{
exception.printStackTrace();
}
}
}
}
RateAdapter.java
import java.util.ArrayList;
import android.util.Log;
import android.widget.BaseAdapter;
import android.view.*;
import android.widget.*;
import android.content.*;
public class RateAdapter extends BaseAdapter
{
private LayoutInflater inflater;
private ArrayList<RateBean> list ;
public RateAdapter()
{
}
public RateAdapter(Context context , ArrayList<RateBean> list )
{
this.inflater = LayoutInflater.from(context);
this.list = list;
}
#Override
public int getCount()
{
return list.size();
}
#Override
public Object getItem(int position)
{
return list.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
public static class ViewHolder
{
TextView currency_name;
TextView cash_buy;
TextView cash_sold;
TextView spot_buy;
TextView spot_sold;
}
#Override
public View getView( int position , View convertView , ViewGroup parent)
{
ViewHolder holder;
if(convertView == null)
{
convertView = inflater.inflate(R.layout.rate_item , null);
holder = new ViewHolder();
holder.currency_name = (TextView)convertView.findViewById(R.id.xml_currency);
holder.cash_buy = (TextView)convertView.findViewById(R.id.xml_cashBuy);
holder.cash_sold = (TextView)convertView.findViewById(R.id.xml_cashSold);
holder.spot_buy = (TextView)convertView.findViewById(R.id.xml_spotBuy);
holder.spot_sold = (TextView)convertView.findViewById(R.id.xml_spotSold);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
RateBean rateItem = list.get(position);
holder.currency_name.setText(rateItem.getCurrency());
holder.cash_buy.setText(rateItem.getCashBuy());
holder.cash_sold.setText(rateItem.getCashSold());
holder.spot_buy.setText(rateItem.getSpotBuy());
holder.spot_sold.setText(rateItem.getSpotSold());
return convertView;
}
}
activity_main.xml
<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:id="#+id/title_textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="銀行查詢選擇"/>
<ListView
android:id="#+id/lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
activity_rate_show.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/updateTime_textView"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:hint="updateTime"/>
<Button
android:id="#+id/fresh_button"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="onClick"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="#string/button_fresh"/>
</LinearLayout>>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp">
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1.5"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/currency"/>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/cash_buy"/>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/cash_sold"/>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/spot_buy"/>
<TextView
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/spot_sold"/>
</LinearLayout>
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
rate_item.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/xml_currency"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1.25"
android:textAppearance="?android:attr/textAppearanceLarge"
android:hint="text"/>
<TextView
android:id="#+id/xml_cashBuy"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:hint="text"/>
<TextView
android:id="#+id/xml_cashSold"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:hint="text"/>
<TextView
android:id="#+id/xml_spotBuy"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:hint="text"/>
<TextView
android:id="#+id/xml_spotSold"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceMedium"
android:hint="text"/>
</LinearLayout>
<ListView
android:id="#+id/lv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Your listview needs a height, it cannot be wrap_content. Give it a height like 500dp or match_parent.
i am a beginner in android programming and i made a custom list view which should present the user details by searching function. while i search the the user i get only the name and the mobile of the user but the default images is not presenting.
this is what i get:
and this is what i would like to get:
this is the layout for the each row in the list:
<?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="fill_parent" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ffffffff"
>
<ImageView
android:id="#+id/profileImage"
android:layout_width="80dp"
android:layout_height="80dp"
android:src="#drawable/camera"
android:background="#drawable/border"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="10dp"
android:textColor="#000000"
android:textSize="16dp"
android:text="Full name"
android:layout_marginTop="5dp"
android:layout_marginLeft="10dp"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/profileImage"
android:layout_toEndOf="#+id/profileImage" />
<TextView
android:id="#+id/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:textColor="#000000"
android:textSize="14dp"
android:text="User details"
android:layout_toRightOf="#+id/profileImage"
android:layout_alignBottom="#+id/profileImage"
android:layout_toLeftOf="#+id/imageButtonInviteUser"
android:layout_toStartOf="#+id/imageButtonInviteUser"
android:layout_below="#+id/title" />
<ImageButton
android:layout_width="80dp"
android:layout_height="80dp"
android:src="#drawable/add_user_50"
android:id="#+id/imageButtonInviteUser"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:background="#drawable/border"/>
<View
android:id="#+id/divider2"
android:layout_below="#+id/profileImage"
android:layout_width="fill_parent"
android:layout_marginTop="1dp"
android:layout_height="6dp"
android:background="#android:color/darker_gray"/>
</RelativeLayout>
</RelativeLayout>
main layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/editTextSearch"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="Search..." />
<View
android:id="#+id/divider1"
android:layout_below="#+id/editTextSearch"
android:layout_width="fill_parent"
android:layout_height="6dp"
android:background="#android:color/darker_gray"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/divider1"
android:id="#+id/scrollViewListView"
android:fillViewport="true"
android:layout_above="#+id/linearLayoutBtn">
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/listViewusers"
android:layout_below="#+id/divider1"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</ScrollView>
<View
android:id="#+id/divider2"
android:layout_below="#+id/scrollViewListView"
android:layout_width="fill_parent"
android:layout_height="6dp"
android:background="#android:color/darker_gray"/>
<LinearLayout
android:id="#+id/linearLayoutBtn"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<Button android:text="Save"
android:id="#+id/ButtonSave"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
</Button>
<Button android:text="Discard"
android:id="#+id/ButtonDiscard"
android:layout_toRightOf="#+id/ButtonSave"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
</Button>
</LinearLayout>
</RelativeLayout>
custom adapter:
/**
* Created by matant on 9/24/2015.
*/
import java.util.List;
import com.example.matant.gpsportclient.R;
import com.example.matant.gpsportclient.Utilities.InviteUsersListRow;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
public class InviteUsersArrayAdapter extends ArrayAdapter<InviteUsersListRow> {
Context context;
List<InviteUsersListRow> rowUsers;
public InviteUsersArrayAdapter(Context context,int resourceId, List<InviteUsersListRow> items) {
super(context, resourceId, items);
this.context = context;
this.rowUsers = items;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
ImageButton imgStatus;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
InviteUsersListRow rowItem = (InviteUsersListRow) getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.invite_users_listview_row, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
holder.imageView = (ImageView) convertView.findViewById(R.id.profileImage);
holder.imgStatus = (ImageButton) convertView.findViewById(R.id.imageButtonInviteUser);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageResource(rowItem.getImageId());
holder.imgStatus.setImageResource(rowItem.getImageStatus());
return convertView;
}
#Override
public int getCount() {
return rowUsers.size();
}
#Override
public InviteUsersListRow getItem(int position) {
return rowUsers.get(position);
}
#Override
public long getItemId(int position) {
return rowUsers.indexOf(getItem(position));
}
}
row in list:
package com.example.matant.gpsportclient.Utilities;
/**
* Created by matant on 9/22/2015.
*/
public class InviteUsersListRow {
private int imageId,imagestatus;
private String title;
private String desc;
public InviteUsersListRow(int imageId,int status, String title,String desc){
this.imageId = imageId;
this.title = title;
this.desc = desc;
this.imagestatus = status;
}
public int getImageId() {
return this.imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getImageStatus(){
return this.imagestatus;
}
public void setImagestatus(int imgStatus)
{
this.imagestatus = imgStatus;
}
}
main activity:
package com.example.matant.gpsportclient.Controllers;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import com.example.matant.gpsportclient.AsyncResponse;
import com.example.matant.gpsportclient.R;
import com.example.matant.gpsportclient.Utilities.InviteUsersArrayAdapter;
import com.example.matant.gpsportclient.Utilities.InviteUsersListRow;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class InviteUsersActivity extends AppCompatActivity implements AsyncResponse, View.OnClickListener,AdapterView.OnItemClickListener {
private EditText editTextSearch;
private Button btnSave,btnDiscard;
private ListView usersListView;
private List<InviteUsersListRow> rowUser;
private DBcontroller dbController;
public static final String EXTRA_USERS = "";
ListView listViewUsers;
List<InviteUsersListRow> rowUsers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_invite_users);
editTextSearch = (EditText) findViewById(R.id.editTextSearch);
btnSave = (Button) findViewById(R.id.ButtonSave);
btnDiscard = (Button)findViewById(R.id.ButtonDiscard);
editTextSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
sendDataToDBController();
}
#Override
public void afterTextChanged(Editable s) {
}
});
btnDiscard.setOnClickListener(this);
}
#Override
public void handleResponse(String resStr) {
Log.d("invite_Response", resStr);
if (resStr != null) {
try {
JSONObject json = new JSONObject(resStr);
String flg = json.getString("flag");
Log.d("flag",flg);
switch (flg){
case "user found":{
JSONArray jsonarr = json.getJSONArray("users");
Log.d("array",jsonarr.toString());
rowUsers = new ArrayList<InviteUsersListRow>();
for(int i = 0; i < jsonarr.length();i++){
{
Log.d("user is", jsonarr.getJSONObject(i).toString());
String name = jsonarr.getJSONObject(i).getString("name");
String mobile = jsonarr.getJSONObject(i).getString("mobile");
InviteUsersListRow rowUser = new InviteUsersListRow(R.id.profileImage, R.id.imageButtonInviteUser, name, mobile);
rowUsers.add(rowUser);
}
listViewUsers = (ListView) findViewById(R.id.listViewusers);
InviteUsersArrayAdapter Useradapter = new InviteUsersArrayAdapter(this,R.layout.invite_users_listview_row,rowUsers);
listViewUsers.setAdapter(Useradapter);
listViewUsers.setOnItemClickListener(this);
}
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}else
Log.d("ServiceHandler", "Couldn't get any data from the url");
}
#Override
public void sendDataToDBController() {
String username = editTextSearch.getText().toString();
BasicNameValuePair tagreq = new BasicNameValuePair("tag", "search_user");
BasicNameValuePair name = new BasicNameValuePair("name", username);
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(tagreq);
nameValuePairList.add(name);
dbController = new DBcontroller(this,this);
dbController.execute(nameValuePairList);
}
#Override
public void preProcess() {
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.ButtonDiscard:
{
Intent i = new Intent();
setResult(RESULT_CANCELED,i);;
finish();
}
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}
Replace the below
InviteUsersListRow rowUser = new InviteUsersListRow(R.id.profileImage, R.id.imageButtonInviteUser, name, mobile);
with
InviteUsersListRow rowUser = new InviteUsersListRow(R.drawable.camera, R.drawable.add_user_50, name, mobile);
The pic should be from "R.drawable" not from "R.id"
You should actually set an image resource below and not an id
holder.imageView.setImageResource(rowItem.getImageId());
holder.imgStatus.setImageResource(rowItem.getImageStatus());
In the above code you are not setting a drawable item.
Two issue with List Fragment: 1. I have a class that extends ListFragments.In the onCreated, I am setting my custom Adapter. The issue is that when the user logs in, the adadpter is null and would not have a value until the user searches for an owner. As a result, it throws an exception when it tries to set up the listadapter and it finds the ArrayAdapter object to be null. I have a custome layout that has a listview and a textview, but I still gets the error. See sample code below. I bold the line of code where the issue happens. Also, I bold few other section where I think it may be important to notice.
I implemented Parcelable in the class "Owner" so that I can pass the object as a ParcelableArray. Even though the object is not null, retrieving it in the OwnerDetail class shows null as if I did not pass it it. I've seen several example, but I am not able to get it right. What am I doing wrong here?
Note: If I were to call the AsyncTask in the OwnerDetail class and set the ListAdapter, it will work fine. The issue with that is that it will display a list of owners as soon as the user is logged in which is not the expected behavior. The behavior that I want is to login first, search for an owner, display the owner, double click on an owner, and finally display a list of cars that the owner owns. I am doing this project, so I can learn how to use ListFraments.
// Here is the entire code
package com.mb.carlovers;
import android.os.Parcel;
import android.os.Parcelable;
public class Car implements Parcelable {
private String _make;
private String _model;
private String _year;
public Car()
{
this._make = "";
this._model = "";
this._year = "";
}
public Car(String make)
{
this._make = make;
}
public Car(String make, String year)
{
this._make = make;
this._year = year;
}
public Car(String make, String model, String year)
{
this._make = make;
this._model = model;
this._year = year;
}
//Getters
public String getMake()
{
return _make;
}
public String getModel()
{
return _model;
}
public String getYear()
{
return _year;
}
//Setters
public void setMake(String make)
{
_make = make;
}
public void setModel(String model)
{
_model = model;
}
public void setYear(String year)
{
_year = year;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
}
}
package com.mb.carlovers;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
public class CarDetail extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.customize_layout,container,false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
String[] myCars = {};
super.onActivityCreated(savedInstanceState);
ArrayAdapter<String> carAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_activated_1, myCars);
setListAdapter(carAdapter);
}
}
package com.mb.carlovers;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Login extends Activity implements OnClickListener{
private Button btnLogin;
private EditText etUsername, etPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
initializeVariables();
}
public void initializeVariables()
{
btnLogin = (Button) this.findViewById(R.id.bLogin);
etUsername = (EditText)this.findViewById(R.id.etUserName);
etPassword = (EditText)this.findViewById(R.id.etPassword);
btnLogin.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
#Override
public void onClick(View v) {
Log.i("Tag", "In Onclick Litener");
String uName = etUsername.getText().toString();
String pWord = etPassword.getText().toString();
if(uName.equals("owner") && pWord.equals("1234"))
{
Log.i("Tag", "username =" + uName + "Password =" + pWord);
Intent intent = new Intent(this, People.class);
startActivity(intent);
}
}
}
package com.mb.carlovers;
import android.os.Parcel;
import android.os.Parcelable;
public class Owner implements Parcelable {
private String _firstName;
private String _lastName;
private String _carId;
private Car _car;
public Owner()
{
this._firstName = "";
this._lastName = "";
this._carId = "";
}
public Owner(String lName)
{
this._lastName = lName;
}
public Owner(String lName, String cId)
{
this._lastName = lName;
this._carId = cId;
}
public Owner(String lName, String fName, String cId)
{
this._lastName = lName;
this._firstName = fName;
this._carId = cId;
}
public Owner(String lName, String fName, String cId, Car car)
{
this._lastName = lName;
this._firstName = fName;
this._carId = cId;
this._car = car;
}
//Getters
public String getFirstName()
{
return _firstName;
}
public String getLastName()
{
return _lastName;
}
public String getCarId()
{
return _carId;
}
public Car getCar()
{
return _car;
}
//Setters
public void setFirstName(String fName)
{
_firstName = fName;
}
public void setLastName(String lName)
{
_lastName = lName;
}
public void setCarId(String cId)
{
_carId = cId;
}
public void setCar(Car car)
{
_car = car;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(_firstName);
dest.writeString(_lastName);
dest.writeString(_carId);
dest.writeParcelable(_car, flags);
}
public Owner(Parcel source){
_firstName = source.readString();
_lastName = source.readString();
_carId = source.readString();
_car = source.readParcelable(Car.class.getClassLoader());
}
public class MyCreator implements Parcelable.Creator<Owner> {
public Owner createFromParcel(Parcel source) {
return new Owner(source);
}
public Owner[] newArray(int size) {
return new Owner[size];
}
}
}
package com.mb.carlovers;
import com.mb.carlovers.adapter.OwnerAdapter;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class OwnerDetail extends ListFragment {
OwnerAdapter ownerAdapter = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.customize_layout,container, false);
}
#Override
public void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
#Override
public void onCreate(Bundle savedInstanceState) {
Owner[] myOwners = null;
super.onCreate(savedInstanceState);
Bundle values = getActivity().getIntent().getExtras();
if(values != null)
{
myOwners = (Owner[]) values.getParcelableArray("test");
}
super.onActivityCreated(savedInstanceState);
ownerAdapter = new OwnerAdapter(getActivity(), R.layout.owner_detail , myOwners);
ownerAdapter.notifyDataSetChanged();
}
package com.mb.carlovers;
import java.util.List;
import com.mb.carlovers.asynctask.OnwerAsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
public class People extends FragmentActivity implements OnClickListener, OnItemSelectedListener {
private Button search;
private EditText etSearchBy, etSearchByID;
private Spinner spOption;
private String selectedOption = null;
private TextView tvErrorMessage;
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.people);
InitializeVariables();
}
private void InitializeVariables()
{
etSearchBy = (EditText) this.findViewById(R.id.etByLastName);
etSearchByID = (EditText) this.findViewById(R.id.etCarID);
spOption = (Spinner) this.findViewById(R.id.spOption);
search = (Button) this.findViewById(R.id.bSearch);
search.setOnClickListener(this);
tvErrorMessage = (TextView) this.findViewById(R.id.tvErrorMessage);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.spOptions, android.R.layout.simple_spinner_dropdown_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spOption.setAdapter(adapter);
spOption.setOnItemSelectedListener(this);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onClick(View v) {
String searchByName = etSearchBy.getText().toString();
String searchById = etSearchByID.getText().toString();
if(selectedOption == null || selectedOption == "All")
{
if(searchByName.matches("") || searchById.matches(""))
{
tvErrorMessage.setText("You must select a last name and car id");
} else
{
}
} else if(selectedOption == "Name")
{
if(!searchByName.matches(""))
{
OnwerAsyncTask asynTask = new OnwerAsyncTask();
List<Owner> lt = null;
try {
lt = asynTask.execute("").get();
} catch (Exception e) {
e.printStackTrace();
}
Owner myOwners[] = lt.toArray(new Owner[lt.size()]);
Bundle data = new Bundle();
data.putParcelableArray("test", myOwners);
} else
{
tvErrorMessage.setText("You must enter the last name of the owner.");
}
} else if (selectedOption == "ID")
{
if(!searchById.matches(""))
{
String st = null;
String d = st;
} else
{
tvErrorMessage.setText("You must enter the car id that you'd like to search.");
}
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
switch(pos)
{
case 0:
selectedOption = "All";
break;
case 1:
selectedOption ="Name";
break;
case 2:
selectedOption ="ID";
break;
default:
selectedOption = null;
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
selectedOption ="ALL";
}
}
package com.mb.carlovers.adapter;
import com.mb.carlovers.Car;
import com.mb.carlovers.R;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class CarAdapter extends ArrayAdapter<Car> {
private Context context;
private int layoutResourceId;
private Car data[] = null;
public CarAdapter(Context context, int resource, Car[] data) {
super(context, resource, data);
this.context = context;
this.layoutResourceId = resource;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
CarHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new CarHolder();
holder.tvMake = (TextView) row.findViewById(R.id.tvMake);
holder.tvModel = (TextView) row.findViewById(R.id.tvModel);
holder.tvYear = (TextView) row.findViewById(R.id.tvYear);
row.setTag(holder);
} else
{
holder = (CarHolder) row.getTag();
}
Car item = data[position];
holder.tvMake.setText(item.getMake().toString());
holder.tvModel.setText(item.getModel().toString());
holder.tvYear.setText(item.getYear().toString());
return row;
}
public static class CarHolder
{
TextView tvMake;
TextView tvModel;
TextView tvYear;
}
}
package com.mb.carlovers.adapter;
import com.mb.carlovers.Owner;
import com.mb.carlovers.R;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class OwnerAdapter extends ArrayAdapter<Owner> {
private Context context;
private int layoutResourceId;
private Owner data[] = null;
public OwnerAdapter(Context context, int textViewResourceId,Owner[] data) {
super(context, textViewResourceId, data);
this.context = context;
this.layoutResourceId = textViewResourceId;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
OwnerHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new OwnerHolder();
holder.tvFName = (TextView) row.findViewById(R.id.tvFirstName);
holder.tvLName = (TextView) row.findViewById(R.id.tvLastName);
holder.tvCId = (TextView) row.findViewById(R.id.tvCarID);
row.setTag(holder);
} else
{
holder = (OwnerHolder) row.getTag();
}
Owner item = data[position];
holder.tvFName.setText(item.getFirstName());
holder.tvLName.setText("Example");
holder.tvCId.setText("1");
return row;
}
static class OwnerHolder
{
TextView tvFName;
TextView tvLName;
TextView tvCId;
}
}
package com.mb.carlovers.asynctask;
import java.util.ArrayList;
import java.util.List;
import com.mb.carlovers.Car;
import android.os.AsyncTask;
public class CarAsyncTask extends AsyncTask<String, Void, List<Car>> {
private List<Car> item = null;
#Override
protected List<Car> doInBackground(String... params) {
item = new ArrayList<Car>();
item.add(new Car("Chevy","Caprice","2002"));
item.add(new Car("Chevy","Malibu","2014"));
item.add(new Car("Dodge","Stratus","2002"));
item.add(new Car("Saturn","L300","2004"));
return item;
}
#Override
protected void onPostExecute(List<Car> result) {
super.onPostExecute(result);
}
}
package com.mb.carlovers.asynctask;
import java.util.ArrayList;
import java.util.List;
import com.mb.carlovers.Owner;
import android.os.AsyncTask;
public class OnwerAsyncTask extends AsyncTask<String, Void, List<Owner>> {
private List<Owner> items = null;
#Override
protected List<Owner> doInBackground(String... params) {
try
{
items = new ArrayList<Owner>();
Owner own = new Owner();
own.setFirstName("John");
own.setLastName("Smith");
own.setCarId("1");
items.add(own);
Owner own1 = new Owner();
own1.setFirstName("Samantha");
own1.setLastName("Right");
own1.setCarId("2");
items.add(own1);
Owner own2 = new Owner();
own2.setFirstName("Regie");
own2.setLastName("Miller");
own2.setCarId("3");
items.add(own2);
Owner own3 = new Owner();
own3.setFirstName("Mark");
own3.setLastName("Adam");
own3.setCarId("4");
items.add(own3);
} catch(Exception ex)
{
ex.toString();
}
return items;
}
#Override
protected void onPostExecute(List<Owner> result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
// car_detail.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/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Car Detail Page" />
</LinearLayout>
// car_row.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="horizontal" >
<TextView
android:id="#+id/tvMake"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="#+id/tvModel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="#+id/tvYear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</LinearLayout>
//customize_layout.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" >
<ListView
android:id="#id/android:list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
<TextView
android:id="#id/android:empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No record to be displayed."
/>
</LinearLayout>
//Login.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Login" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="User Name"
android:textSize="30sp"
android:layout_marginTop="10dp"
android:layout_gravity="center"
/>
<EditText
android:id="#+id/etUserName"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:ems="10"
android:layout_gravity="center"
android:layout_marginTop="10dp"
>
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:textSize="30sp"
android:layout_marginTop="10dp"
android:layout_gravity="center"
/>
<EditText
android:id="#+id/etPassword"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:ems="10"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:inputType="textPassword" />
<Button
android:id="#+id/bLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_gravity="center"
android:text="Login" />
</LinearLayout>
//owner_detail.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="horizontal" >
<TextView
android:id="#+id/tvFirstName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TextView" />
<TextView
android:id="#+id/tvLastName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TextView" />
<TextView
android:id="#+id/tvCarID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="TextView" />
</LinearLayout>
// People.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="horizontal" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="1"
>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search by last name"
android:textSize="30sp"
android:layout_marginLeft="10dp"
android:layout_marginTop="15dp"
/>
<EditText
android:id="#+id/etByLastName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search by car id"
android:textSize="30sp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10sp"
/>
<EditText
android:id="#+id/etCarID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:layout_marginLeft="10dp"
android:layout_marginTop="10sp"
/>
<Spinner
android:id="#+id/spOption"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/spOptions"
/>
<TextView
android:id="#+id/tvErrorMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FF0000"
android:layout_marginTop="10dp"
android:text="" />
<Button
android:id="#+id/bSearch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Button" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="2"
>
<fragment
android:id="#+id/fOwnerDetail"
android:name="com.mb.carlovers.OwnerDetail"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
<fragment
android:id="#+id/fragment1"
android:name="com.mb.carlovers.CarDetail"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
/>
</LinearLayout>
</LinearLayout>
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(ownerAdapter);
}
}
Your code has a lot of problems:
1 Never call lifecycle methods on your own like you do in the OwnerDetail class with super.onActivityCreated(savedInstanceState);
2 Bundle values = getActivity().getIntent().getExtras(); ... values.getParcelableArray("test"); will normally fail because this piece of code will get the activity reference, get the Intent that started the activity and then try to find data passed in under the test key in that Intent. You don't pass such data to the People activity so there will be nothing to be found. You'd normally want to pass a Bundle containing the data at the moment of the creation of the fragment.
3 If you use the fragment in the xml layout you'll not be able to use a Bundle to pass data, instead you either add the fragment manually with transactions and then use a Bundle or you create a setter method in the fragment class and use that. So instead of Bundle data = new Bundle(); data.putParcelableArray("test", myOwners);, which does nothing, get a reference to your fragment and pass the myOwners array through a method.
4 Your AsyncTask will be pretty useless if you use them with .get() because the get() method will wait the AsyncTask to finish, blocking the UI tread as well. Instead you should just start the AsyncTask and then in the onPostExecute() pass the data around.
Here is an example with a simple method which will not change most of your code(which will happen if you manually add the fragments):
// where you start the owner asynctask
if(!searchByName.matches("")) {
OnwerAsyncTask asynTask = new OnwerAsyncTask(People.this);
asynTask.execute("");
}
//...
Then change the OnwerAsyncTask like this:
public class OnwerAsyncTask extends AsyncTask<String, Void, List<Owner>> {
private List<Owner> items = null;
private FragmentActivity mActivity;
public OnwerAsyncTask(FragmentActivity activity) {
mActivity = activity;
}
// doInBackground()...
#Override
protected void onPostExecute(List<Owner> result) {
//I'm assuming that items is the data you want to return, so
// find the OwnerDetail fragment and directly assign the data
OwnerDetail fragment = (OwnerDetail)mActivity.getSupportFragmentManager().findFragmentById(R.id.fOwnerDetail);
fragment.setData(); // to setData you'll pass the data you have in the AsyncTask
// the items list? or you transform that into an array?
}
and in the OwnerDetail fragment:
public class OwnerDetail extends ListFragment {
OwnerAdapter ownerAdapter = null;
public void setData() {
// update the adapter, create a new one etc.
}