I've been following this tutorial Android Search Filter ListView Images and Texts Tutorial
with success. I'm trying to implement it in my own activity and get data from the server.
When I'm typing inside the search field, the grid view becomes empty. It's like the List at custom adapter becomes null.
my activity Class
package com.danz.tensai.catalog;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.danz.tensai.catalog.app.MyApplication;
import com.danz.tensai.catalog.helper.Product;
import com.danz.tensai.catalog.helper.SwipeListAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MainActivity extends ActionBarActivity {
private String TAG = MainActivity.class.getSimpleName();
private String URL_TOP_250 = "http://danztensai.hostoi.com/imdb_top_250.php?offset=";
private SwipeRefreshLayout swipeRefreshLayout;
//private ListView listView;
private GridView gridView;
private SwipeListAdapter adapter;
private List<Product> productList;
private ProgressBar spinner;
EditText editsearch;
private int offSet = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = (GridView)findViewById(R.id.gridViewListProduct);
productList = new ArrayList<>();
fetchProduct();
adapter = new SwipeListAdapter(this, productList);
gridView.setAdapter(adapter);
editsearch = (EditText)findViewById(R.id.search);
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
Log.d(TAG,"Text To Search : "+text);
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void fetchProduct() {
spinner = (ProgressBar)findViewById(R.id.progressBar1);
// appending offset to url
String url = URL_TOP_250 + offSet;
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
int rank = movieObj.getInt("rank");
String title = movieObj.getString("title");
String imageURL = movieObj.getString("imageURL");
Product m = new Product(rank, title,imageURL);
productList.add(0, m);
// updating offset value to highest value
if (rank >= offSet)
offSet = rank;
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
// adapter.notifyDataSetChanged();
}
// stopping swipe refresh
// swipeRefreshLayout.setRefreshing(false);
spinner.setVisibility(View.GONE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
// swipeRefreshLayout.setRefreshing(false);
spinner.setVisibility(View.GONE);
}
});
// Adding request to request queue
Log.e(TAG,req.toString() );
MyApplication.getInstance().addToRequestQueue(req);
}
}
and my Custom Adapter
public class SwipeListAdapter extends BaseAdapter {
private Activity activity;
LayoutInflater inflater;
Context mContext;
private List<Product> productList;
private ArrayList<Product> arraylist;
private String TAG = SwipeListAdapter.class.getSimpleName();
//private String[] bgColors;
public SwipeListAdapter(Context context, List<Product> productList) {
//this.activity = activity;
mContext = context;
this.productList = productList;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<Product>();
this.arraylist.addAll(productList);
// bgColors = activity.getApplicationContext().getResources().getStringArray(R.array.movie_serial_bg);
}
public class ViewHolder{
ImageView productImage;
}
#Override
public int getCount() {
return productList.size();
}
#Override
public Object getItem(int location) {
return productList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView==null)
{
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_row,null);
holder.productImage = (ImageView) convertView.findViewById(R.id.productImage);
convertView.setTag(holder);
}else
{
holder
= (ViewHolder) convertView.getTag();
}
new DownloadImageTask((holder.productImage))
.execute(productList.get(position).imageURL);
return convertView;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
productList.clear();
if (charText.length() == 0) {
productList.addAll(arraylist);
} else {
for (Product wp : arraylist) {
if (wp.getTitle().toLowerCase(Locale.getDefault())
.contains(charText)) {
productList.add(wp);
}
}
}
notifyDataSetChanged();
}
}
When you're creating the adapter, in its constructor, you add to the arraylist list the content of productList. At that point(the adapter constructor) the productList is most likely empty as the http request to fetch the json hasn't finished yet. So you end up with an empty arraylist and when you do any filtering on the adapter you'll not see anything because there' nothing to filter.
Don't forget to update the arraylist(from the adapter) when the data finally comes in the onResponse() callback so you have a reference to to it to use it for filtering.
I would advise you to follow other tutorials.
Edit:
Add a "add" method to the adapter to insert the new items:
//In the SwipeListAdapter class add
public void add(Product p) {
productList.add(0, p);
arraylist.add(0, p);
notifyDataSetChyanged();
}
Then in your activity, instead of:
productList.add(0, m);
call:
adapter.add(m);
Related
I am working on an Android app with a steadily growing Code basis; the aim of the app is to scan and process QR Codes and Barcodes on Handheld Devices for Storages (not Smartphones). It hast two Activities that contain major parts of the programmatical logic; hence, I want to store major parts of the Code that contains the Functionality for processing the Scanner input in an external Service, called Scanner Service, implement the methods there and use the methods in other Activites;
however, I have a major issue with the use of Context, getApplicationContext() and the reference of the Activity in the Service and vice versa; although I think I have referenced and initialised the Textviews from the Activity in the Service, the app keeps on crashing with the following error message:
AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.app.Activity.findViewById(int)' on a null object reference
at com.xxxx.ScanService.<clinit>(ScanService.java:16)
I know what it means, but I donĀ“t know how I could access the View
private static TextView content = (TextView) a.findViewById(R.id.content_detail);
in such a way that I can use it in the Service and in the Activity and the app stops crashing.
Therefore, any hints or help would be very much appreciated, thank you in advance.
The MainDetailActivity:
package com.example.xxx_app;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.RecyclerView;
import android.view.MenuItem;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.xxx.ScanService.*;
import static com.xxx.SimpleItemRecyclerViewAdapter.TAGG;
/**
* An activity representing a single Main detail screen. This
* activity is only used on narrow width devices. On tablet-size devices,
* item details are presented side-by-side with a list of items
* in a {#link MainListActivity}.
*/
public class MainDetailActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener,
PopupMenu.OnMenuItemClickListener {
Context context;
private RecyclerView recyclerView;
private RecyclerviewAdapter recyclerviewAdapter;
private RecyclerTouchListener touchListener;
private ListView listView;
public TextView textView4;
public String code;
public static final String TAG = "Barcode ist:" ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_detail);
context = this;
//TextView headerView = findViewById(R.id.txt1);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
EditText editBarcode = (EditText) findViewById(R.id.editText);
TextView content = (TextView) findViewById(R.id.content_detail);
TextView editTextNumber = findViewById(R.id.editTextNumber);
Button addBooking = findViewById(R.id.button);
Button removeBooking = findViewById(R.id.button2);
removeBooking.setEnabled(false);
spinner.setOnItemSelectedListener(this);
//String selectedItem = spinner.getSelectedItem().toString();
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.mockdata, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
String scannedCode = getIntent().getStringExtra("scannedCode");
Log.d(TAG, "scannedCode" + scannedCode);
if (scannedCode != null && (content.getText().toString().equals(""))) {
content.setText(scannedCode);
}
Button btn = findViewById(R.id.imageView4);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(MainDetailActivity.this, v);
popup.setOnMenuItemClickListener(MainDetailActivity.this);
popup.inflate(R.menu.popup_menu);
popup.show();
}
});
editBarcode.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
String code = editBarcode.getText().toString();
if (code.matches("")) //{ if(code.trim().isEmpty())
//|| editBarcode.getText().toString() > 100 )
{
Log.d(TAG, "Code ist leer");
}
if (keyCode == KeyEvent.KEYCODE_ENTER && code.length() > 0) {
editBarcode.setText("");
ScanService.checkEnteredCode(code);
return true;
}
return false;
}
});
recyclerView = findViewById(R.id.recyclerview);
recyclerviewAdapter = new RecyclerviewAdapter(this);
Intent newIntent = getIntent();
String receivedPalNo = newIntent.getStringExtra("palNo");
String receivedNo = newIntent.getStringExtra("no");
String receivedType = newIntent.getStringExtra("type");
String receivedRack = newIntent.getStringExtra("rack");
String receivedCountItems = newIntent.getStringExtra("count_items");
content.setText(receivedCountItems);
RestClient.getPaletteItems(getApplicationContext(),recyclerviewAdapter,receivedPalNo);
Log.d(TAGG,"Intent 1" + receivedPalNo);
Log.d(TAGG, "Intent 2" + receivedNo);
Log.d(TAGG, "Intent 3" + receivedType);
Log.d(TAGG,"Intent 4" + receivedRack);
Log.d(TAGG, "Intent 5" + receivedCountItems);
final ArrayList<Items> itemList = new ArrayList<>();
/*
Items[] items = new Items(12345,123456, 200, 500);
itemList.add(items);*/
recyclerviewAdapter.setItemList((ArrayList<Items>) itemList);
recyclerView.setAdapter(recyclerviewAdapter);
touchListener = new RecyclerTouchListener(this,recyclerView);
RecyclerviewAdapter finalRecyclerviewAdapter = recyclerviewAdapter;
touchListener
.setClickable(new RecyclerTouchListener.OnRowClickListener() {
#Override
public void onRowClicked(int position) {
//Toast.makeText(getApplicationContext(),itemList.get(position), Toast.LENGTH_SHORT).show();
}
#Override
public void onIndependentViewClicked(int independentViewID, int position) {
}
})
.setSwipeOptionViews(R.id.delete_task,R.id.edit_task)
.setSwipeable(R.id.rowFG, R.id.rowBG, new RecyclerTouchListener.OnSwipeOptionsClickListener() {
#Override
public void onSwipeOptionClicked(int viewID, int position) {
switch (viewID){
case R.id.delete_task:
itemList.remove(position);
finalRecyclerviewAdapter.setItemList(itemList);
break;
case R.id.edit_task:
Toast.makeText(getApplicationContext(),"Edit Not Available",Toast.LENGTH_SHORT).show();
break;
}
}
});
recyclerView.addOnItemTouchListener(touchListener);
class StableArrayAdapter extends ArrayAdapter<String> {
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
public StableArrayAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
#Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
#Override
public boolean hasStableIds() {
return true;
}
}
// savedInstanceState is non-null when there is fragment state
// saved from previous configurations of this activity
// (e.g. when rotating the screen from portrait to landscape).
// In this case, the fragment will automatically be re-added
// to its container so we don"t need to manually add it.
// For more information, see the Fragments API guide at:
//
// http://developer.android.com/guide/components/fragments.html
//
String text = getIntent().getStringExtra("palNo");
//headerView.setText(text);
if (receivedType != null && receivedType.equals("FE")) {
ImageView mImgView = findViewById(R.id.id_col_code);
mImgView.setBackgroundResource(R.drawable.backgroun_blue);
}
if (receivedType != null && receivedType.equals("UFE")) {
ImageView mImgView = findViewById(R.id.id_col_code);
mImgView.setBackgroundResource(R.drawable.backgroun_yellow);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(this, "Selected Item: " +item.getTitle(), Toast.LENGTH_SHORT).show();
switch (item.getItemId()) {
case R.id.search_item:
// do your code
return true;
case R.id.upload_item:
// do your code
return true;
case R.id.copy_item:
// do your code
return true;
/* case R.id.print_item:
// do your code
return true;*/
case R.id.share_item:
// do your code
return true;
/*case R.id.bookmark_item:
// do your code
return true;*/
default:
return false;
}
}
public void newDialog(Activity activity) {
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setContentView(R.layout.sortiment_layout);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
Button okButton = dialog.findViewById(R.id.ok);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(getApplicationContext(),"Ok" ,Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
Button cancelButton = dialog.findViewById(R.id.cancel);
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(getApplicationContext(),"Abbrechen" ,Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
dialog.show();
}
public void showDialog(Activity activity) {
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setContentView(R.layout.newcustom_layout);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
Button okButton = dialog.findViewById(R.id.ok);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(getApplicationContext(),"Ok" ,Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
dialog.show();
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
navigateUpTo(new Intent(this, MainListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onResume() {
super.onResume();
recyclerView.addOnItemTouchListener(touchListener);
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}
The ScanService Class:
package com.example.xxx;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.widget.TextView;
public class ScanService {
private static final String TAG = "Scan Service Tag";
private static Context mContext;
private static Activity a = (MainDetailActivity)mContext;
private static TextView content = (TextView)
a.findViewById(R.id.content_detail);
private static TextView editTextNumber = (TextView)
a.findViewById(R.id.editTextNumber);
public ScanService (Context mContext) {
this.mContext = mContext;
}
public static void checkEnteredCode(String code, Activity a) {
content.setText("");
//PSP-H1-EA-F3
if
(code.matches("PSP-\\p{Upper}\\d\\p{Punct}\\p{Upper}\\" +
"p{Upper}\\p{Punct}\\p{Upper}\\p{Digit}")) {
content.setText("");
content.setText(code);
Log.d(TAG, "xxx");
}
if (code.matches("LF-[0-9]*")) {
///LF-(\d+)/gi
content.setText("");
content.setText(code);
Log.d(TAG, "xxx");
}
if (code.matches("PAL-[0-9][0-9][0-9]")) {
content.setText("");
content.setText(code);
Log.d(TAG, "xxx");
}
if (code.matches("P-[0-9][0-9][0-9]")) {
content.setText("");
content.setText(code);
Log.d(TAG, "Palette");
}
if (code.matches("[0-9][0-9][0-9][0-9].[0-9][0-9].+DB")) {
if(editTextNumber == null) {
Log.d(TAG, "xxx");
}
else {
editTextNumber.setText(code);
Log.d(TAG, "xxx");
}
Log.d(TAG, "xxx");
}
if (code.matches("[0-9A-Z]*[0-9]*")) {
//editBarcode.setText("");
//editBarcode.setText(keyCode);
Log.d(TAG, "xxx");
}
if (code.matches("\\d{13}")) {
//newDialog(MainDetailActivity.this);
//editBarcode.setText("");
//editBarcode.setText(keyCode);
if(editTextNumber == null) {
Log.d(TAG, "xxx");
}
else {
editTextNumber.setText(code);
Log.d(TAG, "xxx");
}
Log.d(TAG, "xxx");
}
else {
Log.d(TAG, "xxx");
};
//editBarcode.setText("");
//editBarcode.setText(code);
/* String code = editBarcode.getText().toString();
if (code.matches("")) //{ if(code.trim().isEmpty())
//|| editBarcode.getText().toString() > 100 )
{
Log.d(TAG, "xxx");
}
//}
checkEnteredCode(code);
//editBarcode.setText("");
return Boolean.parseBoolean(code);*/
Log.d(TAG, code);
}
public static void checkEnteredCode(String code) {
}
}
You cannot access any Views from a Service! Views belong to the Activity. This is the wrong application architecture. A Service performs background processing (file I/O, network I/O, computation, etc.). The Activity is responsible for interacting with the user (inputs, display, etc.). If your Service wants to put data on the screen, you've broken the division of responsibilities. Your Service should simply notify your Activity (or any other component that is interested) when data has changed, and the Activity can then update the View itself. You can share data between the Service and your other components in a number of ways, including: event bus, publish/subscribe, shared preferences, broadcast Intents, SQLite database, etc.
i am working of live search with MySQL, JSON. its working fine with local array values. but not working with MySQL. my concern is when user start typing it has to search from data base and show it in listview. bellow is my Adapter for search
import android.content.Context;
import android.content.Intent;
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 java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import zesteve.com.myapplication.R;
import zesteve.com.myapplication.Search;
import zesteve.com.myapplication.VendProfileActivity;
/**
* Created by Ravi Shankar on 6/22/2017.
*/
public class SearchAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<Search> vendersearchlist = null;
private ArrayList<Search> arraylist;
public SearchAdapter(Context context,
List<Search> vendersearchlist) {
mContext = context;
this.vendersearchlist = vendersearchlist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<Search>();
this.arraylist.addAll(vendersearchlist);
}
public class ViewHolder {
TextView id;
TextView vname;
}
#Override
public int getCount() {
return vendersearchlist.size();
}
#Override
public Search getItem(int position) {
return vendersearchlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.search_item_list, null);
// Locate the TextViews in listview_item.xml
//holder.id = (TextView) view.findViewById(R.id.id);
holder.vname = (TextView) view.findViewById(R.id.autoCompleteTextView);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
//holder.rank.setText(Search.get(position).getRank());
holder.vname.setText(vendersearchlist.get(position).getVname());
// Listen for ListView Item Click
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(mContext, VendProfileActivity.class);
// Pass all data rank
intent.putExtra("Vend_Id",
(vendersearchlist.get(position).getId()));
// Pass all data country
intent.putExtra("Vend_Name",
(vendersearchlist.get(position).getVname()));
// Pass all data population
// Start SingleItemView Class
mContext.startActivity(intent);
}
});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
vendersearchlist.clear();
if (charText.length() == 0) {
vendersearchlist.addAll(arraylist);
} else {
for (Search sl : arraylist) {
if (sl.getVname().toLowerCase(Locale.getDefault())
.contains(charText)) {
vendersearchlist.add(sl);
}
}
}
notifyDataSetChanged();
}
}
AND POJO
public class Search {
private int id;
private String vname;
public Search(int id, String vname) {
this.id = id;
this.vname = vname;
}
public int getId() {
return this.id;
}
public String getVname() {
return this.vname;
}
}
And my SearchActivity.java
import android.content.res.Resources;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import zesteve.com.myapplication.adapter.SearchAdapter;
import zesteve.com.myapplication.adapter.VenderAdapter;
public class Search_vender extends AppCompatActivity {
String catname,city;
int catid;
private EditText Vendname;
private Session session;
ListView listview;
SearchAdapter adapter;
int[] id;
String[] vname;
ArrayList<Search> vendersearchlist = new ArrayList<Search>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_vender);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
session = new Session(Search_vender.this);
catid = getIntent().getIntExtra("CatId",00);
catname= getIntent().getStringExtra("CatName");
city = session.getUserLocation().get(session.KEY_UCITY);
listview = (ListView) findViewById(R.id.listview);
Vendname = (EditText) findViewById(R.id.searchitem);
Vendname.setHint("Search "+catname+" in "+city);
//fetch data from server in json
String vsearch = Vendname.getText().toString();
prepareVender(vsearch);
// Pass results to ListViewAdapter Class
adapter = new SearchAdapter(this, vendersearchlist);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Locate the EditText in listview_main.xml
Vendname.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = Vendname.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
}
private void prepareVender(String sText){
AsyncTask<String,Void,Void> task = new AsyncTask<String, Void, Void>() {
#Override
protected Void doInBackground(String... strings) {
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://api.zesteve.com/vend_list.php?city="+city+"&catid="+catid+"&name="+strings[0])
.build();
try{
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i=0; i<array.length(); i++){
JSONObject object= array.getJSONObject(i);
Search vender = new Search(object.getInt("id"),
object.getString("name"));
vendersearchlist.add(vender);
}
}catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
System.out.println("End of Catagory");
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
adapter.notifyDataSetChanged();
}
};
task.execute(sText);
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
Please comment if you have any doubts.
if Somebody looking for same Solution. bellow is my code
public class Search_vender extends AppCompatActivity {
String catname,city;
int catid;
SearchView Vendname;
private Session session;
ListView listview;
SearchAdapter adapter;
ArrayList<Search> vendersearchlist = new ArrayList<Search>();
ArrayList<Search> filteredSearchResults = new ArrayList<Search>();
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_vender);
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
session = new Session(Search_vender.this);
progressDialog = new ProgressDialog(Search_vender.this);
progressDialog.setCancelable(false);
catid = getIntent().getIntExtra("CatId",00);
catname= getIntent().getStringExtra("CatName");
city = session.getUserLocation().get(session.KEY_UCITY);
//Toast.makeText(Search_vender.this,catid + city,Toast.LENGTH_LONG).show();
listview = (ListView) findViewById(R.id.listview);
Vendname = (SearchView) findViewById(R.id.searchitem);
Vendname.setQueryHint("Search "+catname+" in "+city);
Vendname.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
//Toast.makeText(Search_vender.this, String.valueOf(hasFocus),Toast.LENGTH_SHORT).show();
}
});
Vendname.setOnQueryTextListener(new OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if(newText.length() > 2){
listview.setVisibility(View.VISIBLE);
GetDataVender gv = (GetDataVender) new GetDataVender().execute(newText);
}else{
listview.setVisibility(View.INVISIBLE);
}
return false;
}
});
}
public void filterSearchArray(String newText){
String pName;
filteredSearchResults.clear();
for (int i = 0; i < vendersearchlist.size(); i++)
{
pName = vendersearchlist.get(i).getVname().toLowerCase();
if ( pName.contains(newText.toLowerCase()))
{
filteredSearchResults.add(vendersearchlist.get(i));
}
}
}
class GetDataVender extends AsyncTask<String, Void, String>{
String textsearch;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setMessage("Loading Please Wait...");
showDialog();
}
#Override
protected String doInBackground(String... strings) {
OkHttpClient client = new OkHttpClient();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://api.zesteve.com/autosearch.php?city="+city+"&catid="+catid+"&name="+strings[0])
.build();
this.textsearch = strings[0];
try {
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i=0; i<array.length(); i++){
JSONObject object =array.getJSONObject(i);
Search catagory = new Search(object.getInt("id"),
object.getString("name"));
vendersearchlist.add(catagory);
}
}catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
System.out.println("End of Catagory");
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result != null && result.equalsIgnoreCase("Exception Caught")){
Toast.makeText(Search_vender.this, "Unable to connect to server,please try later", Toast.LENGTH_LONG).show();
hideDialog();
}else{
filterSearchArray(textsearch);
listview.setAdapter(new SearchAdapter(Search_vender.this,filteredSearchResults));
hideDialog();
}
//hideDialog();
//adapter.notifyDataSetChanged();
}
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
it works when user stat search from second character.
I created a listView which is updated on click on item in Reycleview within same page.
Date fetch is working,json data is getting and updated in adpater,but new items is extended with previous data in listview
Layout
First row is RecycleView and Below is Listview, Listview should be update when click on item above in recycleview
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.sharanjit.fitness.R;
import com.google.gson.JsonArray;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
public class AllExercise extends AppCompatActivity {
ListView list;
ProgressDialog dialog;
Context context;
GetJSONData getJSONData;
String[] name = {"Abdominals","Arms","Back","Chest","Shoulders","Legs","Cardio"};
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
AllExerciseAdapter adapter;
ArrayList<Exercise> arrayList;
boolean first=true;
int pos=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.allexercises);
dialog=new ProgressDialog(this);
context=getApplicationContext();
getJSONData=new GetJSONData();
arrayList=new ArrayList<>();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mRecyclerView = (RecyclerView) findViewById(R.id.recycle);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL, false);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyAdapter();
mRecyclerView.setAdapter(mAdapter);
new FetchData().execute();
list = (ListView) findViewById(R.id.exercise_list);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent=new Intent(AllExercise.this,ExerciseView.class);
startActivity(intent);
}
});
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id=item.getItemId();
if(id==16908332)
{
finish();
}
return super.onOptionsItemSelected(item);
}
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
public class ViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
public ViewHolder(View v) {
super(v);
imageView = (ImageView)v.findViewById(R.id.imageView11);
}
}
public MyAdapter() {
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.exercise_item, parent, false);
final ViewHolder vh = new ViewHolder(v);
vh.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pos=vh.getAdapterPosition();
first=false;
new FetchData().execute();
}
});
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final ViewHolder viewHolder=holder;
viewHolder.imageView.setImageResource(Constants.exercise_images[position]);
}
#Override
public int getItemCount() {
return 7;
}
}
public class AllExerciseAdapter extends ArrayAdapter {
final private Context cx;
final private int pos;
AllExerciseAdapter(Context cx,int pos) {
super(cx, R.layout.allexercise_list_item, arrayList);
this.cx = cx;
this.pos=pos;
}
#Override
public View getView(int position, View vw, ViewGroup group) {
vw = View.inflate(cx, R.layout.allexercise_list_item, null);
ImageView imageView=(ImageView)vw.findViewById(R.id.imageView11);
TextView title=(TextView)vw.findViewById(R.id.textView14);
TextView cat=(TextView)vw.findViewById(R.id.textView13);
title.setText(arrayList.get(position).names);
cat.setText(arrayList.get(position).category);
if(position==0)
Log.e("MS",title.getText().toString());
return vw;
}
}
private class FetchData extends AsyncTask<String,String,String>
{
String url="";
String data="";
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("In Progress...");
dialog.setCancelable(false);
dialog.show();
url="http://www.searchdata.in/fitness/get-exercises.php";
try {
data = URLEncoder.encode("category", "UTF-8") + "=" + URLEncoder.encode(name[pos], "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(String... params) {
String s= getJSONData.getData(url,data);
return s;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("sss",s);
try {
JSONArray array=new JSONArray(s);
for(int i=0;i<array.length();i++)
{
JSONObject object=array.getJSONObject(i);
Exercise exercise=new Exercise();
exercise.names=object.getString("name");
exercise.category=object.getString("category");
exercise.decription=object.getString("description");
arrayList.add(exercise);
}
dialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("ss",""+first);
adapter = new AllExerciseAdapter(context,pos);
if(!first) {
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
else {
list.setAdapter(adapter);
}
}
}
private class Exercise
{
public String names;
public String decription;
public String category;
public String imagePath;
}
}
Just Change your onPostExecute method by below code.
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("sss",s);
try {
arrayList=new ArrayList<>();
JSONArray array=new JSONArray(s);
for(int i=0;i<array.length();i++)
{
JSONObject object=array.getJSONObject(i);
Exercise exercise=new Exercise();
exercise.names=object.getString("name");
exercise.category=object.getString("category");
exercise.decription=object.getString("description");
arrayList.add(exercise);
}
dialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("ss",""+first);
adapter = new AllExerciseAdapter(context,pos);
list.setAdapter(adapter);
/*if(!first)
{
adapter.notifyDataSetChanged();
}
else {
list.setAdapter(adapter);
}*/
}
You need to make a small change in your code -
if(!first) {
list.setAdapter(adapter);
adapter.notifyDataSetChanged(); // No needed to do for first time
}
else {
list.setAdapter(adapter); // Need to call only once.
adapter.notifyDataSetChanged();// Here you need to call it to reflect changes
}
One more change you need to do in onPostExecute -
try {
JSONArray array=new JSONArray(s);
arraList.clear(); //Add this line
for(int i=0;i<array.length();i++)
Hope it will help :)
This Line Is working for the code:-
adapter = new AllExerciseAdapter(context,arrayList);
adapter.setNotifyOnChange(true); // <-----
list.setAdapter(adapter);
I am loading a ListView through a ContentProvider and SimpleCursorAdapter. I have added a TextWatcher to filter results. This works fine, however after I click on a ListItem to load another fragment, when I hit back I get an empty ListView. Any ideas why this is happening?
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockListFragment;
import com.brndwgn.RequestHelper.GetResponse;
import com.brndwgn.database.BlogContentProvider;
import com.brndwgn.database.BlogTable;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
public class NewsFragment extends SherlockListFragment implements LoaderCallbacks<Cursor> {
public boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) parent.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
private SimpleCursorAdapter adapter;
private boolean dataRetrieved;
private SlidingArea parent;
PullToRefreshListView pullToRefreshView;
EditText searchBox;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
parent = (SlidingArea) getActivity();
setHasOptionsMenu(true);
parent.getSupportActionBar().setCustomView(R.layout.actionbar_news_list);
parent.getSupportActionBar().setDisplayShowCustomEnabled(true);
parent.getSupportActionBar().setDisplayShowTitleEnabled(false);
parent.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final ImageView searchButton = (ImageView) parent.findViewById(R.id.image_search_list);
searchButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
searchBox.setVisibility(View.VISIBLE); }
});
final ImageView refreshButton = (ImageView) parent.findViewById(R.id.image_refresh_list);
refreshButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getData(getString(R.string.json_get_posts_url), true);
refreshButton.setImageResource(R.drawable.menu_refresh_dark);
fillData();
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.fragment_news, null);
pullToRefreshView = (PullToRefreshListView) V.findViewById(R.id.pull_to_refresh_listview);
searchBox = (EditText)V.findViewById(R.id.edittext_search);
return V;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
pullToRefreshView.setOnRefreshListener(new OnRefreshListener<ListView>() {
#Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
// Do work to refresh the list here.
getData(getString(R.string.json_get_posts_url), false);
}
});
}
#Override
public void onResume() {
super.onResume();
fillData();
parent.getSupportActionBar().setCustomView(R.layout.actionbar_news_list);
parent.getSupportActionBar().setDisplayShowCustomEnabled(true);
parent.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final ImageView searchButton = (ImageView) parent.findViewById(R.id.image_search_list);
searchButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
searchBox.setVisibility(View.VISIBLE);
}
});
final ImageView refreshButton = (ImageView) parent.findViewById(R.id.image_refresh_list);
refreshButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getData(getString(R.string.json_get_posts_url), true);
refreshButton.setImageResource(R.drawable.menu_refresh_dark);
fillData();
}
});
adapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
String[] projection = new String[] { BlogTable.TITLE_PLAIN, BlogTable.DATE_MODIFIED, BlogTable.EXCERPT, BlogTable.ID };
return parent.getContentResolver().query(BlogContentProvider.CONTENT_URI, projection, BlogTable.TITLE_PLAIN + " LIKE '%"+constraint+"%'", null, BlogTable.DATE_MODIFIED + " DESC");
}
});
searchBox.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
//Constant used as key for ID being passed in the bundle between fragments
public static final String NEWS_ID = "newsID";
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Bundle detailBundle = new Bundle();
detailBundle.putLong(NEWS_ID, id);
FragmentTransaction ft = parent.getSupportFragmentManager().beginTransaction();
//Instance must be created here to setArguments rather then in the replace() method
NewsDetailFragment newsDetailFragment = new NewsDetailFragment();
newsDetailFragment.setArguments(detailBundle);
ft.replace(R.id.content_frame, newsDetailFragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}
private void getData(String url, boolean showProgressDialog) {
new Request(showProgressDialog).execute(new String[] {url});
}
public class Request extends AsyncTask<String, Void, String> {
ProgressDialog dialog;
/* This is the only file that needs to be edited */
private GetResponse response = null;
private boolean showProgressDialog = true;
public Request(boolean showProgressDialog)
{
super();
this.showProgressDialog = showProgressDialog;
response = new GetResponse();
}
#Override
protected void onPreExecute() {
if (showProgressDialog) {
dialog = new ProgressDialog(parent);
dialog.setMessage("Loading stuff to read...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
}
//This method must return the type specified in the constructor
#Override
protected String doInBackground(String... url) {
response.setUrl(url[0]);
String res = response.execute();
// When it returns the "res" it will call onPostExecute
return res;
}
#Override
protected void onPostExecute(String result) {
// Here we have response from server
if ( isNetworkAvailable() ){
try {
JSONObject json = new JSONObject(result);
JSONArray arr = json.getJSONArray("posts");
for (int i = arr.length() - 1; i >= 0; --i) {
JSONObject row = arr.getJSONObject(i);
if (row.getString("type").equals("post")) {
if (row.getString("status").equals("publish")) {
ContentValues values = new ContentValues();
values.put(BlogTable.POST_ID, row.getString("id"));
values.put(BlogTable.URL, row.getString(BlogTable.URL));
values.put(BlogTable.TITLE, row.getString(BlogTable.TITLE));
values.put(BlogTable.TITLE_PLAIN, Html.fromHtml(row.getString(BlogTable.TITLE_PLAIN)).toString());
values.put(BlogTable.CONTENT, row.getString(BlogTable.CONTENT));
values.put(BlogTable.EXCERPT, Html.fromHtml(row.getString(BlogTable.EXCERPT)).toString());
values.put(BlogTable.DATE, row.getString(BlogTable.DATE));
values.put(BlogTable.DATE_MODIFIED, row.getString(BlogTable.DATE_MODIFIED));
//getAuthorID
JSONObject objAuthor = row.getJSONObject("author");
values.put(BlogTable.AUTHOR_ID, objAuthor.getInt("id"));
//Check to insert new author
//getThumbnail
byte[] image = AppHelper.getBlobFromURL(row.getString(BlogTable.THUMBNAIL));
if (image != null) {
values.put(BlogTable.DATE_MODIFIED, image);
}
//isFavourite
values.put(BlogTable.IS_FAVOURITE, 0);
// when this is called here it is referring to the activity
parent.getContentResolver().insert(BlogContentProvider.CONTENT_URI, values);
dataRetrieved = true;
}
else {
String currentID = row.getString("id");
// Delete unpublished fields
parent.getContentResolver().delete(BlogContentProvider.CONTENT_URI, "_id = " + currentID, null);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else {
Toast toast = Toast.makeText( parent , "Oops! There is no connection to the Internet", Toast.LENGTH_SHORT);
toast.show();
}
// Call onRefreshComplete when the list has been refreshed.
pullToRefreshView.onRefreshComplete();
super.onPostExecute(result);
ImageView refreshButton = (ImageView) parent.findViewById(R.id.image_refresh_list);
refreshButton.setImageResource(R.drawable.menu_refresh);
if (showProgressDialog) {
dialog.dismiss();
}
}
}
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
String[] projection = new String[] { BlogTable.TITLE_PLAIN, BlogTable.DATE_MODIFIED, BlogTable.EXCERPT, BlogTable.ID };
CursorLoader loader = new CursorLoader(parent, BlogContentProvider.CONTENT_URI, projection, null, null, BlogTable.DATE_MODIFIED + " DESC");
return loader;
}
private void fillData(){
//_id is expected from this method that is why we used it earlier
String[] from = new String[] { BlogTable.TITLE_PLAIN, BlogTable.DATE_MODIFIED, BlogTable.EXCERPT};
int[] to = new int[] { R.id.text_news_title, R.id.text_news_date, R.id.text_news_excerpt};
//initialize loader to call this class with a callback
getLoaderManager().initLoader(0, null, this);
//We create adapter to fill list with data, but we don't provide any data as it will be done by loader
adapter = new SimpleCursorAdapter(parent, R.layout.news_list_view, null, from, to, 0);
setListAdapter(adapter);
}
public void onLoadFinished(Loader<Cursor> arg0, Cursor data) {
adapter.swapCursor(data);
}
public void onLoaderReset(Loader<Cursor> arg0) {
adapter.swapCursor(null);
}
}
What the Adapter sees:
The reason why you observe an empty ListView is because the position of the Cursor that was returned is STILL pointing at the last element. When you swap() the Cursor to an Adapter, the Adapter tries to iterate using a while(Cursor.moveToNext()) loop. Because that loop always evaluates FALSE, your ListView gives you the illusion of an empty Cursor.
Print the values of Cursor.getCount() and Cursor.getPosition() in onLoadFinished(). If I am correct, these two values should be equal. This clash of indexes creates the above illusion.
Why does the Adapter see this:
Loaders will re-use a Cursor whenever possible. If you request a Loader for a set of data that has not changed, the loader is smart and return the Cursor via onLoadFinished without doing any additional work, not even setting the position of the Cursor to -1.
ANS Call Cursor.moveToPosition(-1) in onLoadFinished() manually to work around this problem.
this is my code to display listview in customized format .but my requirement is when ever i clicked on any of the item of listview its further details need to be displayed but when am clicking on it ....its not at all getting effected i mean no setonitemclicklictener event is performed ....
i request please have a look on my code which is given above ....thanks to all
package com.hands;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Passengers extends Activity implements OnClickListener{
ListView lview3;
Button btn;
int textlength = 0;
ArrayList<String> text_sort = new ArrayList<String>();
ArrayList<Integer> image_sort = new ArrayList<Integer>();
ArrayList<String> text_sort2 = new ArrayList<String>();
EditText edittext;
private static String month[] = {"kareem","Saleem","Imran","Anwar","Shahid",
"Raheem","Afzal","Nazeer","Ahmed"};
private static String desc[] = {"ssagi123,Indian","ssagi1234,Indian","ssagi1235,Indian",
"ssagi1236,Indian","ssagi1237,Indian","ssagi1238,Indian","ssagi1239,Indian",
"ssagi12310,Indian","ssagi123411,Indian","Month - 10"};
int[] image = { R.drawable.user2, R.drawable.user2, R.drawable.user2,
R.drawable.user2, R.drawable.user2, R.drawable.user2, R.drawable.user2,
R.drawable.user2, R.drawable.user2, R.drawable.user2 };
/* private static String bstatus[] = {"no status","no status","no status","no status","no status",
"no status","no status","no status","no status"};
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.passengers);
System.out.println("****1");
btn=(Button)findViewById(R.id.psnbutt1);
btn.setOnClickListener(this);
edittext = (EditText) findViewById(R.id.search_mycontact);
lview3 = (ListView) findViewById(R.id.listView3);
System.out.println("****2");
lview3.setAdapter(new ListViewCustomAdapter(image, month, desc));
edittext.addTextChangedListener(new TextWatcher()
{
public void afterTextChanged(Editable s)
{
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after)
{
}
public void onTextChanged(CharSequence s, int start,
int before, int count)
{
textlength = edittext.getText().length();
text_sort.clear();
image_sort.clear();
text_sort2.clear();
for (int i = 0; i < month.length; i++)
{
if (textlength <= month[i].length())
{
if (edittext.getText().toString().
equalsIgnoreCase((String) month[i].subSequence(0, textlength)))
{
text_sort.add(month[i]);
image_sort.add(image[i]);
text_sort2.add(desc[i]);
}
}
}
System.out.println("****3");
lview3.setAdapter(new ListViewCustomAdapter(image_sort, text_sort, text_sort2));
}
});
System.out.println("****4");
lview3.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
System.out.println("****5");
// Object listItem = lview3.getItemAtPosition(position);
//String keyword=listItem.toString();
// Toast.makeText(getApplicationContext(), "you are selected"+keyword, Toast.LENGTH_LONG).show();
}
});
}
class ListViewCustomAdapter extends BaseAdapter
{
String[] title;
String[] description;
int[] number;
Activity context;
LayoutInflater inflater;
ListViewCustomAdapter()
{
}
ListViewCustomAdapter(int[] image, String[] month, String[] desc)
{
title = month;
description=desc;
number=image;
}
ListViewCustomAdapter(ArrayList<Integer> image,ArrayList<String> month, ArrayList<String> desc)
{
title = new String[month.size()];
description=new String[desc.size()];
number = new int[image.size()];
for(int i=0;i<month.size();i++)
{
title[i] = month.get(i);
description[i]=desc.get(i);
number[i] = image.get(i);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return title.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row=convertView;
row = inflater.inflate(R.layout.listitem_row2, parent, false);
TextView textview = (TextView) row.findViewById(R.id.txtViewTitle);
TextView textview1 = (TextView) row.findViewById(R.id.txtViewDescription);
System.out.println("before list row statement");
//final ListView lview3=(ListView) row.findViewById(R.id.listView3);
// final ListView lview3=(ListView)findViewById(R.id.listView3);
System.out.println("after list row statement");
ImageView imageview = (ImageView) row.findViewById(R.id.imgViewLogo);
textview.setText(title[position]);
textview1.setText(description[position]);
imageview.setImageResource(number[position]);
/*lview3.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
Object listItem = lview3.getItemAtPosition(position);
String keyword=listItem.toString();
Toast.makeText(getApplicationContext(), "you are selected"+keyword, Toast.LENGTH_LONG).show();
}
});
*/
return (row);
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.psnbutt1:
Intent i = new Intent(this, NewhapploginActivity.class);
startActivity(i);
break;
}
}
}
You need to add
android:focusable="false"
android:focusableInTouchMode="false"
to all the View's of your row.xml.Because in Custom ListView as the View over it are having the focus so ListView is not able to get its focus working.