how get value of textview (with currentview ) in viewpager?
Problem
i gettext of textview but now current showing textview its gee=ttingtext of next view's textview
class Test
package "name";
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by name on 26-Mar-16.
*/
public class Test extends Activity {
private static final String DB_NAME = "";
private static final String TABLE_NAME = "";
private SQLiteDatabase database;
private List<String> testContactName = new ArrayList<>();
public MyAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
ViewPager mViewPager = (ViewPager) findViewById(R.id.testvp);
mAdapter = new MyAdapter();
mViewPager.setAdapter(mAdapter);
mViewPager.setCurrentItem(0);
mViewPager.setOffscreenPageLimit(50);
getAllContacts();
}
public void getAllContacts() {
DatabaseHelper dbOpenHelper = new DatabaseHelper(this, DB_NAME);
database = dbOpenHelper.openDataBase();
String query = "select * from " + TABLE_NAME;
Cursor cursor = database.rawQuery(query, null);
if (cursor != null) {
cursor.moveToFirst();
for (int c = 0; c < cursor.getCount(); c++) {
String name = cursor.getString(cursor.getColumnIndex("content"));
cursor.moveToNext();
/* String count= String.valueOf(cursor.getCount());
Toast.makeText(getApplicationContext(), count , Toast.LENGTH_LONG).show();*/
testContactName.add(name);
// testContactName.notifyAll();
Log.i("Name: " + "" + "---", name);
}mAdapter.notifyDataSetChanged();
}
cursor.close();
}
private class MyAdapter extends PagerAdapter {
public MyAdapter() {
super();
}
#Override
public int getCount() {
return testContactName.size();
}
#Override
public boolean isViewFromObject(View collection, Object object) {
return object == collection;
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.test1, null);
TextView pagenumber;
pagenumber = (TextView) view.findViewById(R.id.tv_test1);
try {
pagenumber.setText(testContactName.get(position));
**method i called like**
imgcopy.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
setClipboard(mViewPager.getFocusedChild(), pagenumber.getText().toString());
}
});
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
( collection).addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
( collection).removeView((View) view);
mAdapter.notifyDataSetChanged();
}
}
}
method i use to copytoclipborad
private void setClipboard(View context,String text) {
if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.setText(text);
Toast.makeText(getApplicationContext(),text,Toast.LENGTH_LONG).show();
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData.newPlainText("Copied Text", text);
clipboard.setPrimaryClip(clip);
Toast.makeText(getApplicationContext(),"Copied To ClipBoard",Toast.LENGTH_LONG).show();
}
}
test.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.view.ViewPager
android:id="#+id/testvp"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</RelativeLayout>
test1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/tv_test1"
android:layout_gravity="top|center"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Related
i am working on small project. I inserted .sqlite database file in assets folder and getting information in listview. Now i have to display image with text. I created imageview in xml file, then add some function in my code. But it doesn't work. Here is source.
MainActivity.java
package com.example.arlequina.sqlitefromassetexample;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.Toast;
import com.example.arlequina.sqlitefromassetexample.adapter.ListProductAdapter;
import com.example.arlequina.sqlitefromassetexample.database.DatabaseHelper;
import com.example.arlequina.sqlitefromassetexample.model.Product;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
/**
* Created by ARLEQUINA on 2/10/2017.
*/
public class MainActivity extends Activity {
private ListView lvProduct;
private ListProductAdapter adapter;
private List<Product> mProductList;
private DatabaseHelper mDBHelper;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvProduct = (ListView)findViewById(R.id.listview_product);
mDBHelper = new DatabaseHelper(this);
//Check exists database
File database = getApplicationContext().getDatabasePath(DatabaseHelper.dbname);
if(false == database.exists()){
mDBHelper.getReadableDatabase();
//Copy db
if(copyDatabase(this)){
Toast.makeText(this,"Copy database success", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Copy data error", Toast.LENGTH_SHORT).show();
return;
}
}
//Get product list in db when db exists
mProductList = mDBHelper.getListProduct();
//Init adapter
adapter = new ListProductAdapter(this,mProductList);
//Set adapter for listview
lvProduct.setAdapter(adapter);
}
private boolean copyDatabase(Context context){
try{
InputStream inputStream = context.getAssets().open(DatabaseHelper.dbname);
String outFileName = DatabaseHelper.dblocation + DatabaseHelper.dbname;
OutputStream outputStream = new FileOutputStream(outFileName);
byte[] buff = new byte[1024];
int length = 0;
while((length = inputStream.read(buff)) > 0){
outputStream.write(buff, 0, length);
}
outputStream.flush();
outputStream.close();
Log.v("MainActivity", "DB copied");
return true;
} catch(Exception e){
e.printStackTrace();
return false;
}
}
}
Product.java
package com.example.arlequina.sqlitefromassetexample.model;
import java.sql.Blob;
/**
* Created by ARLEQUINA on 2/10/2017.
*/
public class Product {
private int id;
private String name;
private String price;
private String desc;
private Blob img;
public Product(int id, String name, String price, String desc, Blob img){
this.id = id;
this.name = name;
this.price = price;
this.desc = desc;
this.img = img;
}
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getPrice(){
return price;
}
public void setPrice(String price){
this.price = price;
}
public String getDesc(){
return desc;
}
public void setDesc(){
this.desc = desc;
}
public Blob getImage(){
return img;
}
public void setImage(Blob img){
this.img = img;
}
}
DatabaseHelper.java
package com.example.arlequina.sqlitefromassetexample.database;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.arlequina.sqlitefromassetexample.model.Product;
import java.util.ArrayList;
import java.util.List;
import java.sql.Blob;
/**
* Created by ARLEQUINA on 2/10/2017.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String dbname = "sample.db";
public static final String dblocation = "/data/data/com.example.arlequina.sqlitefromassetexample/databases/";
private Context mContext;
private SQLiteDatabase mDatabase;
public DatabaseHelper(Context context){
super(context, dbname, null, 1);
this.mContext = context;
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public void openDatabase(){
String dbPath = mContext.getDatabasePath(dbname).getPath();
if(mDatabase != null && mDatabase.isOpen()){
return;
}
mDatabase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}
public void closeDatabase(){
if(mDatabase != null){
mDatabase.close();
}
}
public List<Product> getListProduct(){
Product product = null;
List<Product> productList = new ArrayList<>();
openDatabase();
Cursor cursor = mDatabase.rawQuery("SELECT * FROM Product", null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
product = new Product(cursor.getInt(0), cursor.getString(1), cursor.getString(2),cursor.getString(3),cursor.getBlob(4));
productList.add(product);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return productList;
}
}
ListProductAdapter.java
package com.example.arlequina.sqlitefromassetexample.adapter;
import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.arlequina.sqlitefromassetexample.R;
import com.example.arlequina.sqlitefromassetexample.model.Product;
import org.w3c.dom.Text;
import java.util.List;
/**
* Created by ARLEQUINA on 2/10/2017.
*/
public class ListProductAdapter extends BaseAdapter{
private Context mContext;
private List<Product> mProductList;
public ListProductAdapter(Context mContext, List<Product> mProductList){
this.mContext = mContext;
this.mProductList = mProductList;
}
#Override
public int getCount() {
return mProductList.size();
}
#Override
public Object getItem(int position) {
return mProductList.get(position);
}
#Override
public long getItemId(int position) {
return mProductList.get(position).getId();
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
View v = View.inflate(mContext, R.layout.item_listview, null);
TextView tvName = (TextView)v.findViewById(R.id.tv_product_name);
TextView tvPrice = (TextView)v.findViewById(R.id.tv_product_price);
TextView tvDesc = (TextView)v.findViewById(R.id.tv_product_desc);
ImageView tvImage = (ImageView)v.findViewById(R.id.tv_product_img);
tvName.setText(mProductList.get(position).getName());
tvPrice.setText(String.valueOf(mProductList.get(position).getPrice()) + " $");
tvDesc.setText(mProductList.get(position).getDesc());
// tvImage.setImageIcon(mProductList.get(position).getImage());
return v;
}
}
item_listview.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"
android:background="#ffffff"
android:paddingBottom="5dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_product_name"
android:text = "Name"
android:textColor="#4bb6d6"
android:textSize="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id = "#+id/tv_product_price"
android:text="100$"
android:textColor="#b30000"
android:textSize="18dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id = "#+id/tv_product_desc"
android:text="Description"
android:textSize="16dp"
android:textStyle="italic"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id = "#+id/tv_product_img"
android:layout_gravity="right"
android:paddingRight="10dp"
android:paddingBottom="10dp"/>
</LinearLayout>
activity_main.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"
android:background="#d1d1d1">
<ListView
android:id = "#+id/listview_product"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:divider="#d1d1d1"
android:dividerHeight="10dp"></ListView>
</LinearLayout>
And here is image of sqlite database attached file picture.
enter image description here
Here is database source. database name is "sample", and table product.
CREATE TABLE `Product` (
`ID` INTEGER PRIMARY KEY AUTOINCREMENT,
`Name` TEXT,
`Price` TEXT,
`Desc` TEXT,
`Image` BLOB
);
cursor.getBlob() returns a byte[] array, use BitmapFactory.decodeByteArray() method to convert byte array to an image . In your Product.java change the img type from Blob to byte[]. Here's a link to official documentation.
i want to ask about OnClickListener. I called external database file[assets folder] in listview. I want to set onClicklistener at each item in listview. When listview item clicks, wanna appear a little fragment with data fields.I tried many sources but still not working.
Here is example fragment want to do.
enter image description here
Here is database structure.
enter image description here
Here is DatabaseHelper.java
package com.example.arlequina.sqlitefromassetexample.database;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.example.arlequina.sqlitefromassetexample.model.Product;
import java.util.ArrayList;
import java.util.List;
import java.sql.Blob;
/**
* Created by ARLEQUINA on 2/10/2017.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String dbname = "sample.db";
public static final String dblocation = "/data/data/com.example.arlequina.sqlitefromassetexample/databases/";
private Context mContext;
private SQLiteDatabase mDatabase;
public DatabaseHelper(Context context){
super(context, dbname, null, 1);
this.mContext = context;
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public void openDatabase(){
String dbPath = mContext.getDatabasePath(dbname).getPath();
if(mDatabase != null && mDatabase.isOpen()){
return;
}
mDatabase = SQLiteDatabase.openDatabase(dbPath, null, SQLiteDatabase.OPEN_READWRITE);
}
public void closeDatabase(){
if(mDatabase != null){
mDatabase.close();
}
}
public List<Product> getListProduct(){
Product product = null;
List<Product> productList = new ArrayList<>();
openDatabase();
Cursor cursor = mDatabase.rawQuery(" SELECT * FROM Product ", null);
cursor.moveToFirst();
while(!cursor.isAfterLast()){
product = new Product(cursor.getInt(0), cursor.getString(1), cursor.getString(2),cursor.getString(3));
productList.add(product);
cursor.moveToNext();
}
cursor.close();
closeDatabase();
return productList;
}
}
Here is ListProductAdapter.java
package com.example.arlequina.sqlitefromassetexample.adapter;
import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.arlequina.sqlitefromassetexample.R;
import com.example.arlequina.sqlitefromassetexample.model.Product;
import org.w3c.dom.Text;
import java.util.List;
/**
* Created by ARLEQUINA on 2/10/2017.
*/
public class ListProductAdapter extends BaseAdapter{
private Context mContext;
private List<Product> mProductList;
public ListProductAdapter(Context mContext, List<Product> mProductList){
this.mContext = mContext;
this.mProductList = mProductList;
}
#Override
public int getCount() {
return mProductList.size();
}
#Override
public Object getItem(int position) {
return mProductList.get(position);
}
#Override
public long getItemId(int position) {
return mProductList.get(position).getId();
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
View v = View.inflate(mContext, R.layout.item_listview, null);
TextView tvName = (TextView)v.findViewById(R.id.tv_product_name);
TextView tvPrice = (TextView)v.findViewById(R.id.tv_product_price);
TextView tvDesc = (TextView)v.findViewById(R.id.tv_product_desc);
//ImageView tvImage = (ImageView)v.findViewById(R.id.tv_product_img);
tvName.setText(mProductList.get(position).getName());
tvPrice.setText(String.valueOf(mProductList.get(position).getPrice()) + " $");
tvDesc.setText(mProductList.get(position).getDesc());
// tvImage.setImageIcon(mProductList.get(position).getImage());
return v;
}
}
Here is MainActivity
package com.example.arlequina.sqlitefromassetexample;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.arlequina.sqlitefromassetexample.adapter.ListProductAdapter;
import com.example.arlequina.sqlitefromassetexample.database.DatabaseHelper;
import com.example.arlequina.sqlitefromassetexample.model.Product;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
/**
* Created by ARLEQUINA on 2/10/2017.
*/
public class MainActivity extends Activity {
private ListView lvProduct;
private ListProductAdapter adapter;
private List<Product> mProductList;
private DatabaseHelper mDBHelper;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvProduct = (ListView)findViewById(R.id.listview_product);
mDBHelper = new DatabaseHelper(this);
//Check exists database
File database = getApplicationContext().getDatabasePath(DatabaseHelper.dbname);
if(false == database.exists()){
mDBHelper.getReadableDatabase();
//Copy db
if(copyDatabase(this)){
Toast.makeText(this,"Copy database success", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Copy data error", Toast.LENGTH_SHORT).show();
return;
}
}
//Get product list in db when db exists
mProductList = mDBHelper.getListProduct();
//Init adapter
adapter = new ListProductAdapter(this,mProductList);
//Set adapter for listview
lvProduct.setAdapter(adapter);
}
private boolean copyDatabase(Context context){
try{
InputStream inputStream = context.getAssets().open(DatabaseHelper.dbname);
String outFileName = DatabaseHelper.dblocation + DatabaseHelper.dbname;
OutputStream outputStream = new FileOutputStream(outFileName);
byte[] buff = new byte[1024];
int length = 0;
while((length = inputStream.read(buff)) > 0){
outputStream.write(buff, 0, length);
}
outputStream.flush();
outputStream.close();
Log.v("MainActivity", "DB copied");
return true;
} catch(Exception e){
e.printStackTrace();
return false;
}
}
}
item_listview.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"
android:background="#ffffff"
android:paddingBottom="5dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="5dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_product_name"
android:text = "Name"
android:textColor="#4bb6d6"
android:textSize="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id = "#+id/tv_product_price"
android:text="100$"
android:textColor="#b30000"
android:textSize="18dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id = "#+id/tv_product_desc"
android:text="Description"
android:textSize="16dp"
android:textStyle="italic"/>
</LinearLayout>
activity_main.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"
android:background="#d1d1d1">
<ListView
android:id = "#+id/listview_product"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:divider="#d1d1d1"
android:dividerHeight="10dp"></ListView>
</LinearLayout>
Product.java
package com.example.arlequina.sqlitefromassetexample.model;
import java.sql.Blob;
/**
* Created by ARLEQUINA on 2/10/2017.
*/
public class Product {
private int id;
private String name;
private String price;
private String desc;
//private Blob img;
public Product(int id, String name, String price, String desc){
this.id = id;
this.name = name;
this.price = price;
this.desc = desc;
//this.img = img;
}
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getPrice(){
return price;
}
public void setPrice(String price){
this.price = price;
}
public String getDesc(){
return desc;
}
public void setDesc(String desc){
this.desc = desc;
}
}
Since your problem is make your list item clickable, you can use this after init listview in activity.
lvProduct.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
position is position of that clicked item in list. So you can get that item using mProductList.get(position)
After you can get that item, now it's time to show your item up. You can use custom dialog to make it like your demo (of cause you have to create 1 more xml):
Check section Custom Dialog in this official link: https://developer.android.com/guide/topics/ui/dialogs.html
You can use listview.setOnItemClickListener or v.setOnClickListener to solve your problem.That is the most basic ,man.
i want to use google api when i enter keyword it must give me city names with that keyword i want to use this by using StartActivityForResult()
here is my code i have reached so far: but i don't know what to do next, i have the api key and i have used the key in my manifest file i just want to complete the coding part!
case R.id.linearPlace:{ startActivityForResult(new Intent(this,Location.class),CITY);
}break;
}
}
public void onActivityResult(int requestcode,int resultcode,Intent intent ){
super.onActivityResult(requestcode,resultcode,intent);
String geoName = intent.getStringExtra("");
}
here i am putting my code for simple search address on edittext change event
Layout File : activity_demo.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="match_parent"
android:padding="10dp"
tools:context="com.skandinaviske.elevkalender.DemoActivity">
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/actLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Key word" />
<EditText
android:id="#+id/edtCountryCode"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Country Name" />
</LinearLayout>
<ListView
android:id="#+id/lstAddress"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/linearLayout2"></ListView>
</RelativeLayout>
Class File : DemoActivity.java
package com.demo.pack;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class DemoActivity extends Activity {
private RequestQueue mRequestQueue;
private EditText actLocation;
public ArrayList<HashMap<String, String>> listofAddress;
private ListView lstAddress;
private EditText edtCountryCode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo);
mRequestQueue = Volley.newRequestQueue(this);
actLocation = (EditText) findViewById(R.id.actLocation);
edtCountryCode = (EditText) findViewById(R.id.edtCountryCode);
lstAddress = (ListView) findViewById(R.id.lstAddress);
actLocation.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) {
if (actLocation.getText().toString().length() > 3) {
String url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + actLocation.getText().toString().trim() + "%20" + edtCountryCode.getText().toString() + "&key=API_KEY&language=en_us";
fetchJsonResponse(url);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private void fetchJsonResponse(String s) {
// Pass second argument as "null" for GET requests
JsonObjectRequest req = new JsonObjectRequest(s, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//String result = "Your IP Address is " + response.getString("ip");
Log.d("response==>", response.toString());
calldisplayList(response);
//Toast.makeText(EditProfileActivity.this, response.toString(), Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage() + "");
}
});
/* Add your Requests to the RequestQueue to execute */
mRequestQueue.add(req);
}
private void calldisplayList(JSONObject response) {
String city = "", state = "", country = "";
if (response != null) {
try {
if (response.getString("status").toString().equals("OK")) {
JSONArray adddressArray = response.getJSONArray("results");
if (adddressArray.length() != 0) {
if (listofAddress == null) {
listofAddress = new ArrayList<>();
}
listofAddress.clear();
for (int i = 0; i < adddressArray.length(); i++) {
JSONObject jsonObject = adddressArray.getJSONObject(i);
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("address", jsonObject.getString("formatted_address").toString());
listofAddress.add(hashMap);
}
if (listofAddress.size() != 0 && actLocation.getText().length() != 0) {
AddressListAdapter addressListAdapter = new AddressListAdapter(DemoActivity.this, listofAddress);
lstAddress.setAdapter(addressListAdapter);
lstAddress.setVisibility(View.VISIBLE);
} else {
lstAddress.setVisibility(View.GONE);
}
} else {
}
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
}
}
public class AddressListAdapter extends BaseAdapter {
private final Activity context;
private final ArrayList<HashMap<String, String>> listOfAddress;
private class ViewHolder {
TextView txtAddress;
}
public AddressListAdapter(Activity context1, ArrayList<HashMap<String, String>> listOfAddress) {
this.context = context1;
this.listOfAddress = listOfAddress;
}
#Override
public int getCount() {
return listOfAddress.size();
}
#Override
public Object getItem(int position) {
return listOfAddress.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
ViewHolder viewHolder;
View converView = view;
if (converView == null) {
LayoutInflater infalInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
converView = infalInflater.inflate(R.layout.address_list_item, null);
viewHolder = new ViewHolder();
viewHolder.txtAddress = (TextView) converView.findViewById(R.id.txtAddress);
converView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) converView.getTag();
}
viewHolder.txtAddress.setText(listOfAddress.get(position).get("address") + "");
return converView;
}
}
}
Layout File for Adapter : address_list_item.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:id="#+id/txtAddress"
android:layout_width="match_parent"
android:background="#color/white"
android:textColor="#color/black"
android:text="temp data"
android:gravity="center_vertical"
android:layout_height="wrap_content"
android:padding="5dp" />
</LinearLayout>
Don't miss to put API_KEY (Hear is the url from where you can get API key : https://developers.google.com/maps/documentation/geocoding/get-api-key#get-an-api-key )
I'm struggling with this problem and didn' find any solution browsing the web and lots of other similar posts in StackOverflow
No error compiling, after a serach in the app no Views are visible in the ListView (browsing both ListView and CustomAdapter objects, result items views are present, but are not shown in the app's listview)
here the code:
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.lightelements.carddroid">
<permission android:name="com.lightelements.carddroid.cards.provider.READWRITE"/>
<uses-permission android:name="com.lightelements.carddroid.cards.provider.READWRITE"/>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.default_searchable"
android:value=".SearchableActivity" />
</activity>
<activity android:name=".SearchActivity"
android:parentActivityName=".MainActivity"
android:label="#string/search_cards_title">
</activity>
<activity android:name=".SearchableActivity">
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data android:name="android.app.searchable"
android:resource="#xml/searchable"/>
</activity>
<provider
android:authorities="com.lightelements.carddroid.cards.provider"
android:name="com.lightelements.carddroid.CardProvider"
android:exported="true"
android:readPermission="com.lightelements.carddroid.cards.provider.READWRITE"
android:writePermission="com.lightelements.carddroid.cards.provider.READWRITE"
/>
</application>
</manifest>
res/xml/searchable.xml
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/
android"android:label="#string/app_name"
android:hint="#string/search_hint" >
</searchable>
search_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:layout_marginTop="10dp"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="#+id/searchLayoutTestText"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ListView android:id="#+id/searchResultsList"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
simple_card.xml
<?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="match_parent">
<TextView
android:id="#+id/card_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="#dimen/card_name"
/>
</LinearLayout>
SearchableActivity
package com.lightelements.carddroid;
import android.app.SearchManager;
import android.content.ContentResolver;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;
import java.util.List;
/**
* Created by User on 20/09/2015.
*/
public class SearchableActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<Card>> {
private static final String LOG_TAG = SearchableActivity.class.getSimpleName();
private CardsCustomAdapter mCardsCustomAdapter;
private static int LOADER_ID = 2;
private ContentResolver mContentResolver;
private List<Card> cardsRetrieved;
private ListView listView;
private String matchText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(LOG_TAG, "Entered Searchable Activity");
setContentView(R.layout.search_layout);
TextView testText = (TextView) findViewById(R.id.searchLayoutTestText);
testText.setText("OK SEARCHLIST LAYOUT");
Intent intent = getIntent();
// ACTION SEARCH PER CONFERMA SELEZIONE //
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
Log.v(LOG_TAG,"query: " + query);
mContentResolver = getContentResolver();
mCardsCustomAdapter = new CardsCustomAdapter(SearchableActivity.this, getSupportFragmentManager());
listView = (ListView) findViewById(R.id.searchResultsList);
listView.setAdapter(mCardsCustomAdapter);
matchText = query.toString();
getSupportLoaderManager().initLoader(LOADER_ID++, null, SearchableActivity.this);
}
}
#Override
public Loader<List<Card>> onCreateLoader(int id, Bundle args) {
return new CardsSearchListLoader(SearchableActivity.this, CardContract.URI_TABLE, this.mContentResolver, matchText);
}
#Override
public void onLoadFinished(Loader<List<Card>> loader, List<Card> cards) {
mCardsCustomAdapter.setData(cards);
this.cardsRetrieved = cards;
}
#Override
public void onLoaderReset(Loader<List<Card>> loader) {
mCardsCustomAdapter.setData(null);
}
}
MainActivity
package com.lightelements.carddroid;
import android.app.Activity;
import android.app.SearchManager;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks,
BestPrice.OnFragmentInteractionListener {
private static final String LOG_TAG = MainActivity.class.getSimpleName();
private NavigationDrawerFragment mNavigationDrawerFragment;
TextView mData = null;
Fragment activeFragment = null;
LinearLayout activeLayout = null;
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
// Connect to Database
String[] projection = {BaseColumns._ID,
CardContract.CardColumns.CARD_NAME,
CardContract.CardColumns.CARD_SET,
CardContract.CardColumns.SET_CODE,
CardContract.CardColumns.MULTIVERSE_ID,
CardContract.CardColumns.MKM_ID
};
ContentResolver mContentResolver = getContentResolver();
Cursor mTestCursor = mContentResolver.query(CardContract.URI_TABLE, projection, null, null, null);
Log.d(LOG_TAG,"Completato on Create.");
if (mTestCursor.moveToFirst()) {
String card_name = mTestCursor.getString(mTestCursor.getColumnIndex(CardContract.CardColumns.CARD_NAME));
TextView testView = (TextView) findViewById(R.id.testTextView);
testView.setText(card_name);
}
}
#Override
public void onNavigationDrawerItemSelected(int position) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
public void onSectionAttached(int number) {
Fragment fragment = null;
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
fragment = BestPrice.newInstance("param1", "param2");
break;
case 2:
mTitle = "TEST SEZIONE 2";
fragment = PlaceholderFragment.newInstance(number + 1);
break;
case 3:
mTitle = getString(R.string.title_section3);
fragment = PlaceholderFragment.newInstance(number + 1);
break;
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
public void onFragmentInteraction(Uri uri){
}
public void dataSearch(View view){
Activity fragment = (Activity) view.getContext();
mData = (TextView) fragment.findViewById(R.id.best_price_data);
activeLayout = (LinearLayout) findViewById(R.id.fragment_best_price_layout);
}
public void dataOut(String outData){
mData.setText(outData);
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
getMenuInflater().inflate(R.menu.main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
MenuItem searchItem = menu.findItem(R.id.searchCards);
SearchView cardSearchView = (SearchView) MenuItemCompat.getActionView(searchItem);
cardSearchView.setSearchableInfo(searchManager.getSearchableInfo(new ComponentName(this, SearchableActivity.class)));
Log.d(LOG_TAG,"Searchable created");
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
CardSearchListLoader
package com.lightelements.carddroid;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;
import android.support.v4.content.AsyncTaskLoader;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* Created by User on 06/09/2015.
*/
public class CardsSearchListLoader extends AsyncTaskLoader<List<Card>> {
private static final String LOG_TAG = CardsSearchListLoader.class.getSimpleName();
private List<Card> mCards;
private ContentResolver mContentResolver;
private Cursor mCursor;
private String mFilterText;
public CardsSearchListLoader(Context context, Uri uri, ContentResolver contentResolver, String filterText){
super(context);
mContentResolver = contentResolver;
mFilterText = filterText;
}
#Override
public List<Card> loadInBackground() {
String[] projection = {BaseColumns._ID,
CardContract.CardColumns.CARD_NAME,
CardContract.CardColumns.CARD_SET,
CardContract.CardColumns.SET_CODE,
CardContract.CardColumns.MULTIVERSE_ID,
CardContract.CardColumns.MKM_ID
};
List<Card> entries = new ArrayList<Card>();
String selection = CardContract.CardColumns.CARD_NAME + " LIKE '%" + mFilterText + "%'";
mCursor = mContentResolver.query(CardContract.URI_TABLE, projection, selection, null, null);
if (mCursor!=null) {
if (mCursor.moveToFirst()) {
do {
int _id = mCursor.getInt(mCursor.getColumnIndex(BaseColumns._ID));
String card_name = mCursor.getString(mCursor.getColumnIndex(CardContract.CardColumns.CARD_NAME));
int card_set = mCursor.getInt(mCursor.getColumnIndex(CardContract.CardColumns.CARD_SET));
String set_code = mCursor.getString(mCursor.getColumnIndex(CardContract.CardColumns.SET_CODE));
int multiverse_id = mCursor.getInt(mCursor.getColumnIndex(CardContract.CardColumns.MULTIVERSE_ID));
int mkm_id = mCursor.getInt(mCursor.getColumnIndex(CardContract.CardColumns.MKM_ID));
Card card = new Card(_id, card_name, card_set, set_code, multiverse_id, mkm_id);
entries.add(card);
} while (mCursor.moveToNext());
}
}
return entries;
}
#Override
public void deliverResult(List<Card> cards) {
if (isReset()){
if (cards!=null){
mCursor.close();
}
}
Log.d(LOG_TAG,"deliverResult");
List<Card> oldCardList = mCards;
if (mCards == null || mCards.size() == 0) {
Log.d(LOG_TAG, "++++++++++++++ No Ddata returned");
}
mCards = cards;
if (isStarted()) {
super.deliverResult(cards);
}
if (oldCardList != null || oldCardList != cards) {
mCursor.close();
}
}
#Override
protected void onStartLoading() {
if (mCards != null) {
deliverResult(mCards);
}
if (takeContentChanged() || mCards == null) {
forceLoad();
}
}
#Override
protected void onStopLoading() {
cancelLoad();
}
#Override
protected void onReset() {
onStopLoading();
if (mCursor != null) {
mCursor.close();
}
mCards = null;
}
#Override
public void onCanceled(List<Card> cards) {
super.onCanceled(cards);
if (mCursor != null) {
mCursor.close();
}
}
#Override
public void forceLoad() {
super.forceLoad();
}
}
CardsCustomAdapter
package com.lightelements.carddroid;
import android.content.Context;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by User on 11/09/2015.
*/
public class CardsCustomAdapter extends ArrayAdapter<Card> {
private LayoutInflater mLayoutInflater;
private static FragmentManager sFragmentManager;
public CardsCustomAdapter(Context context, FragmentManager fragmentManager){
super(context, android.R.layout.simple_list_item_2);
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
sFragmentManager = fragmentManager;
}
public CardsCustomAdapter(Context context){
super(context, android.R.layout.simple_list_item_2);
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final View view;
if (convertView == null) {
view = mLayoutInflater.inflate(R.layout.custom_card, parent, false);
} else {
view = convertView;
}
final Card card = getItem(position);
final int _id = card.getId();
final String name = card.getCard_name();
((TextView) view.findViewById(R.id.card_name)).setText(name);
return view;
}
public void setData(List<Card> cards){
clear();
if (cards != null) {
for (Card card : cards) {
add(card);
}
}
}
}
Your search layout heights should be inverted:
<?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:layout_marginTop="10dp"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="#+id/searchLayoutTestText"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<ListView android:id="#+id/searchResultsList"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
//this is JOBListAdapter class
package com.example.hellotest.adapters;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.hellotest.R;
import com.example.hellotest.model.Job;
public class JobListAdapter extends BaseAdapter {
private LayoutInflater mInflater ;
private List<Job> mJobs;
private SimpleDateFormat mDateFormat;
private SimpleDateFormat mInputFormat;
private String mPosterPrefix;
public JobListAdapter(Context context) {
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mDateFormat = new SimpleDateFormat("dd MMMM yyyy", Locale.US);
mInputFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.US);
mPosterPrefix = context.getString(R.string.job_posted_by);
}
public void setJobList(List<Job> jobs) {
mJobs = jobs;
}
#Override
public int getCount() {
if(null != mJobs) {
return mJobs.size();
}
return 0;
}
#Override
public Object getItem(int position) {
return mJobs.get(position);
}
#Override
public long getItemId(int position) {
return mJobs.get(position).getId();
}
//this is the method where I think that the problem is please somebody tell me.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(null == convertView) {
convertView = mInflater.inflate(R.layout.job_list_row, null);
holder = new ViewHolder();
holder.created = (TextView) convertView.findViewById(R.id.job_listing_date);
holder.location = (TextView) convertView.findViewById(R.id.job_listing_location);
holder.title = (TextView) convertView.findViewById(R.id.job_listing_title);
holder.experience = (TextView) convertView.findViewById(R.id.job_listing_experience);
holder.poster = (TextView) convertView.findViewById(R.id.job_listing_posted_by);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
updateRow(holder, mJobs.get(position));
return convertView;
}
private void updateRow(ViewHolder holder, Job job) {
holder.title.setText(job.getTitle());
int id = job.isPremium() ? R.drawable.icon_premium : 0;
holder.created.setText(getDate(job.getCreated()));
holder.created.setCompoundDrawablesWithIntrinsicBounds(0, 0, id, 0);
holder.experience.setText(job.getExperience());
holder.location.setText(job.getLocation());
holder.poster.setText(mPosterPrefix + job.getPoster());
}
private CharSequence getDate(String created) {
try {
return mDateFormat.format(mInputFormat.parse(created));
} catch (ParseException e) {
e.printStackTrace();
}
return created;
}
private static class ViewHolder {
TextView created;
TextView title;
TextView location;
TextView experience;
TextView poster;
}
}
// layout for fragmentjob_listing even I make the listview height to fill_parent as suggested when I googled the solution for the issue.
<?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" >
<LinearLayout
android:id="#+id/job_listing_filter_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/job_listing_tab_bg"
android:gravity="center_vertical"
android:minHeight="48dp" >
<TextView
android:id="#+id/job_listing_experience"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#drawable/selector_job_listing_tab"
android:clickable="true"
android:gravity="center"
android:text="#string/job_listing_experience" />
<ImageView
android:id="#+id/space2"
android:layout_width="1dp"
android:layout_height="match_parent"
android:contentDescription="#string/app_name"
android:scaleType="fitXY"
android:src="#drawable/job_listing_horizontal_divider" />
<TextView
android:id="#+id/job_listing_location"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#drawable/selector_job_listing_tab"
android:clickable="true"
android:gravity="center"
android:text="#string/job_listing_location" />
</LinearLayout>
<ImageView
android:id="#+id/imageView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:contentDescription="#string/app_name"
android:scaleType="fitXY"
android:src="#drawable/job_listing_divider" />
<TextView
android:id="#+id/job_listing_message"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center"
android:visibility="gone"/>
<ListView
android:id="#+id/job_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</ListView>
</LinearLayout>
// JobListingFragment Class where the joblistAdapter class called up
package com.example.hellotest;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.example.hellotest.R;
import com.example.hellotest.adapters.JobListAdapter;
import com.example.hellotest.config.Constant;
import com.example.hellotest.io.CookieStringRequest;
import com.example.hellotest.io.json.JobsProcessor;
import com.example.hellotest.model.Job;
import com.example.hellotest.model.JobList;
import com.example.hellotest.model.Pagination;
import com.example.hellotest.tasks.JsonParserTask;
import com.example.hellotest.tasks.JsonParsingListener;
import com.example.hellotest.util.AccountUtils;
import com.example.hellotest.util.Log;
public class JobListingFragment extends Fragment {
public static final String ARG_URL = "argument_url";
public static final String ARG_IS_FILTER_ON = "argument_is_filtered";
public static final String ARG_IS_DEFAULT_JOB_LIST = "argument_is_default_job_list";
public static final String ARG_EMPTY_MESSAGE = "argument_empty_message";
protected static final int REQUEST_EXPERIENCE = 0x11;
protected static final int REQUEST_LOCATION = 0x12;
private ListView mJobsList;
private TextView mMessageView;
private JobListAdapter mAdapter;
private List<Job> mJobs;
private Pagination mPagination;
private boolean mIsFetching;
private boolean mIsDefaultList;
private boolean mIsFilterOn;
private String mUrl;
private String mLocId;
private int mExperienceId = -1;
private ProgressBar mFooterProgress;
private Log mLogger = new Log(JobListingFragment.class);
private Object mRequestTag = new Object();
private RequestQueue mRequestQueue;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAdapter = new JobListAdapter(getActivity());
if (null != savedInstanceState) {
getState(savedInstanceState);
} else {
getState(getArguments());
}
// init();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mRequestQueue = Volley.newRequestQueue(getActivity());
}
#Override
public void onDetach() {
mRequestQueue.cancelAll(mRequestTag);
super.onDetach();
}
#Override
public void onResume() {
init();
super.onResume();
}
private void getState(Bundle bundle) {
mUrl = bundle.getString(ARG_URL);
mIsFilterOn = bundle.getBoolean(ARG_IS_FILTER_ON);
mIsDefaultList = bundle.getBoolean(ARG_IS_DEFAULT_JOB_LIST);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_job_listing, null);
mJobsList = (ListView) view.findViewById(R.id.job_list);
mMessageView = (TextView) view.findViewById(R.id.job_listing_message);
return view;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
View footer = getLayoutInflater(savedInstanceState).inflate(R.layout.paginated_list_footer, null);
mFooterProgress = (ProgressBar) footer.findViewById(R.id.footer_progress);
if (!mIsFilterOn) {
view.findViewById(R.id.job_listing_filter_container).setVisibility(View.GONE);
} else {
view.findViewById(R.id.job_listing_experience).setOnClickListener(mOnClickListener);
view.findViewById(R.id.job_listing_location).setOnClickListener(mOnClickListener);
}
mJobsList.addFooterView(footer);
mJobsList.setAdapter(mAdapter);
mJobsList.setOnScrollListener(mOnScrollListener);
mJobsList.setOnItemClickListener(mOnItemClickListener);
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(ARG_URL, mUrl);
outState.putBoolean(ARG_IS_FILTER_ON, mIsFilterOn);
outState.putBoolean(ARG_IS_DEFAULT_JOB_LIST, mIsDefaultList);
super.onSaveInstanceState(outState);
}
public void startAfresh(String url, boolean isPaginated) {
mLogger.d("old fragment reused");
mIsFilterOn = true;
mUrl = url;
reset();
init();
}
private void init() {
mLocId = AccountUtils.getLocationFilter();
mExperienceId = AccountUtils.getExperienceFilter();
String url = getUrl(1);
fetchJobs(url);
}
private void reset() {
mJobs = null;
mPagination = null;
mAdapter.setJobList(null);
mAdapter.notifyDataSetChanged();
}
private String getUrl(int pageNumber) {
String appender = "";
if (mIsFilterOn) {
if (null != mLocId || -1 < mExperienceId) {
if (null != mLocId) {
appender += "/loc-" + mLocId;
} else {
appender += "/loc-" + 0;
}
if (-1 < mExperienceId) {
appender += "/exp-" + mExperienceId;
} else {
appender += "/exp-" + 0;
}
}
}
String url = mUrl + appender + "/pg-" + pageNumber;
if (mIsDefaultList && AccountUtils.isLoggedIn()) {
url += "?" + Constant.MAP_COOKIE_KEY + "=" + AccountUtils.getCookie();
}
return url;
}
private void fetchJobs(String url) {
mIsFetching = true;
mLogger.d("url :" + url);
int method = mIsDefaultList ? Method.GET : Method.POST;
CookieStringRequest request = new CookieStringRequest(method, url, mListener, mErrorListener);
request.setTag(mRequestTag);
mRequestQueue.add(request);
}
private Response.Listener<String> mListener = new Listener<String>() {
#Override
public void onResponse(String response) {
mLogger.d("response :" + response);
JsonParserTask<JobList> jsonTask = new JsonParserTask<JobList>(new JobsProcessor());
jsonTask.setListener(mJsonListener);
jsonTask.execute(response);
}
};
private Response.ErrorListener mErrorListener = new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mIsFetching = false;
Toast.makeText(getActivity(), R.string.network_error, Toast.LENGTH_LONG).show();
}
};
private JsonParsingListener<JobList> mJsonListener = new JsonParsingListener<JobList>() {
#Override
public void onSuccess(JobList result) {
if (null == mPagination) {
mPagination = result.getPagination();
mPagination.setCurrentPage(0);
if(null == result.getJobs() || 0 == result.getJobs().size()) {
mMessageView.setText(getArguments().getString(ARG_EMPTY_MESSAGE));
mMessageView.setVisibility(View.VISIBLE);
} else {
mMessageView.setVisibility(View.GONE);
}
} else {
mPagination.updateData(result.getPagination());
}
if (null != mJobs) {
mJobs.addAll(result.getJobs());
} else {
mJobs = result.getJobs();
}
mAdapter.setJobList(mJobs);
mAdapter.notifyDataSetChanged();
mIsFetching = false;
}
#Override
public void onFailure(Exception e) {
Toast.makeText(getActivity(), "Unable to process response", Toast.LENGTH_LONG).show();
mIsFetching = false;
}
};
private OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Job job = (Job) mAdapter.getItem(position);
Intent intent = new Intent(getActivity(), JobDetailsActivity.class);
intent.putExtra(JobDetailsActivity.EXTRA_JOB, job);
startActivity(intent);
}
};
// this is the function where I also found that might cause some problem because when I scrolls down the items in the list repeated.
private OnScrollListener mOnScrollListener = new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
boolean loadMore = firstVisibleItem + visibleItemCount >= totalItemCount;
if (loadMore && totalItemCount > 0 && null != mPagination) {
boolean isLastPage = mPagination.getCurrentPage() >= mPagination.getTotalPages();
if (isLastPage) {
mFooterProgress.setVisibility(View.GONE);
}
if (!mIsFetching && !isLastPage) {
fetchJobs(getUrl(mPagination.getCurrentPage()+1));
}
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (Activity.RESULT_OK == resultCode) {
switch (requestCode) {
case REQUEST_EXPERIENCE:
onExperienceSelection(data);
break;
case REQUEST_LOCATION:
onLocationSelection(data);
break;
}
}
}
add one more line in your function:
mjob.clear();
private JsonParsingListener<JobList> mJsonListener = new JsonParsingListener<JobList>() {
#Override
public void onSuccess(JobList result) {
if (null == mPagination) {
mPagination = result.getPagination();
mPagination.setCurrentPage(0);
if(null == result.getJobs() || 0 == result.getJobs().size()) {
mMessageView.setText(getArguments().getString(ARG_EMPTY_MESSAGE));
mMessageView.setVisibility(View.VISIBLE);
} else {
mMessageView.setVisibility(View.GONE);
}
} else {
mPagination.updateData(result.getPagination());
}
if (null != mJobs) {
mJobs.clear();
mJobs.addAll(result.getJobs());
} else {
mJobs = result.getJobs();
}
mAdapter.setJobList(mJobs);
mAdapter.notifyDataSetChanged();
mIsFetching = false;
}