how to Integrate Pull to RefreshListview in Android - java

public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
static final int MENU_MANUAL_REFRESH = 0;
static final int MENU_DISABLE_SCROLL = 1;
static final int MENU_SET_MODE = 2;
private LinkedList<String> mListItems;
//private PullToRefreshView mPullRefreshListView;
// contacts JSONArray
JSONArray contacts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
This is My parsing COde i m able to get String value now i have Put JsonParser class in My project .
public class PullToRefreshListActivity extends Activity {
static final int MENU_MANUAL_REFRESH = 0;
static final int MENU_DISABLE_SCROLL = 1;
static final int MENU_SET_MODE = 2;
private PullToRefreshView mPullRefreshListView;
private ArrayAdapter<String> mAdapter;
private static String url = "http://api.androidhive.info/contacts/";
/** Called when the activity is first created. */
private LinkedList<String> mListItems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pull_to_refresh_listview);
mPullRefreshListView = (PullToRefreshView) findViewById(R.id.pull_refresh_list);
// Set a listener to be invoked when the list should be refreshed.
mPullRefreshListView.setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh() {
mPullRefreshListView.setLastUpdatedLabel(DateUtils
.formatDateTime(getApplicationContext(),
System.currentTimeMillis(),
DateUtils.FORMAT_SHOW_TIME
| DateUtils.FORMAT_SHOW_DATE
| DateUtils.FORMAT_ABBREV_ALL));
// Do work to refresh the list here.
new GetDataTask().execute();
}
});
ListView actualListView = mPullRefreshListView.getRefreshableView();
mListItems = new LinkedList<String>();
mListItems.addAll(Arrays.asList(mStrings));
mAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, mListItems);
// You can also just use setListAdapter(mAdapter)
actualListView.setAdapter(mAdapter);
}
private class GetDataTask extends AsyncTask<Void, Void, String[]> {
#Override
protected String[] doInBackground(Void... params) {
// Simulates a background job.
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
return mStrings;
}
#Override
protected void onPostExecute(String[] result) {
mListItems
.addFirst("Added after refresh..New Version Coming soon J-elly Bean");
mAdapter.notifyDataSetChanged();
// Call onRefreshComplete when the list has been refreshed.
mPullRefreshListView.onRefreshComplete();
super.onPostExecute(result);
}
}
private String[] mStrings = { "A-stro", "B-ender", "C-upcake", "E-clair",
"F-royo", "G-ingerbread", "H-oneycomb", "I-ce Cream Sandwich ",
"Android Versions From iamvijayakumar.blogspot.com" };
}
This is Dummy Example for PullToRefreshListview which i did. Now I want to Integrate so that i can display data in ListView with Pull To Refresh. Can u please help me how to integrate? Where i will place code for parsing and all?? Please help me .

In the Dummy Example, You given simply replace Adapter creation by using the below which is used to set data using Hashmap list. TAG_ID etc are used to be columns. Create an xml with name row and put 4 textview in the row layout and give them names as below which I have used in int array. Then set this adapter to listview.
mAdapter= new SimpleAdapter(this, mylist, R.layout.row,
new String[] {TAG_ID, TAG_NAME, TAG_EMAIL,TAG_PHONE_MOBILE}, new int[]
{R.id.tvtagid, R.id.tvtagname, R.id.tvtagemail,R.id.tvtagphone});
In the above adapter mylist is an Arraylist of your HashMap objects.

Related

getting a error with my code private void update list everything from "this, mCommentList" is underlined in red

Could someone help me. I was following a very long tutorial and got to the end and can't fix this error. Starting at public void update list the code below is underlined in red and I can't seem to correct the problem.
public class readComments extends ListActivity {
private ProgressDialog pDialog;
private static final String READ_COMMENTS_URL = "http://120.120.1.100 /webservice/comments.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_TITLE = "title";
private static final String TAG_POSTS = "posts";
private static final String TAG_POST_ID = "post_id";
private static final String TAG_USERNAME = "username";
private static final String TAG_MESSAGE = "message";
private JSONArray mComments = null;
private ArrayList<HashMap<String, String>> mCommentList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.read_comments);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
//loading the comments via AsyncTask
new LoadComments().execute();
}
public void addComment(View v)
{
Intent i = new Intent(readComments.this, AddComment.class);
startActivity(i);
}
public void updateJSONdata() {
}
private void updateList() {
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(readComments.this);
pDialog.setMessage("Loading Comments...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
public void updateJSONdata() {
mCommentList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
try {
mComments = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_MESSAGE);
String username = c.getString(TAG_USERNAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_MESSAGE, content);
map.put(TAG_USERNAME, username);
mCommentList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
//Problem starts here everything underlined in red
#Override
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.single_post, new String[]{TAG_TITLE, TAG_MESSAGE,
TAG_USERNAME}, new int[]{R.id.title, R.id.message,
R.id.username});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}

How to display the data from mySQL in listview in android?

I can insert data into database but now face the problem that cannot retrieve data from the database and display in listview in android. Here is my coding part for retrieve data. Hope someone can help to solve this, thank you.
package com.example.iuum;
private ProgressDialog pDialog;
private static final String READ_COMMENTS_URL = "http://10.19.229.212/webservice/comments.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_TITLE = "title";
private static final String TAG_POSTS = "posts";
private static final String TAG_POST_ID = "post_id";
private static final String TAG_USERNAME = "username";
private static final String TAG_MESSAGE = "message";
private JSONArray mComments = null;
private ArrayList<HashMap<String, String>> mCommentList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forum1a);
}
#Override
protected void onResume() {
super.onResume();
new LoadComments().execute();
}
public void clickbtnWrite(View v) {
Intent i = new Intent(Forum1a.this, AddForum.class);
startActivity(i);
}
/**
* Retrieves recent post data from the server.
*/
public void updateJSONdata() {
mCommentList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
try {
mComments = json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
// gets the content of each tag
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_MESSAGE);
String username = c.getString(TAG_USERNAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
map.put(TAG_MESSAGE, content);
map.put(TAG_USERNAME, username);
mCommentList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Inserts the parsed data into the listview.
*/
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.singelpost, new String[] { TAG_TITLE, TAG_MESSAGE,
TAG_USERNAME }, new int[] { R.id.title, R.id.message,
R.id.username });
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Forum1a.this);
pDialog.setMessage("Loading Comments...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
}
Add ListView in activity_forum1a.xml
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"></ListView>
Take ListView reference
private ListView mList;
Initialize it in onCreate
mList = (ListView) findViewById(R.id.list_view);
Take ListAdapter class Refernce
private ListAdapter listAdapter;
Add setListAdapter method
public void setListAdapter(ListAdapter listAdapter) {
this.listAdapter = listAdapter;
mList.setAdapter(listAdapter);
}
Change updateList method to
/**
* Inserts the parsed data into the listview.
*/
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.test, new String[] { TAG_TITLE, TAG_MESSAGE,
TAG_USERNAME }, new int[] { R.id.title, R.id.message,
R.id.username });
setListAdapter(adapter);
}
and perform item click operation outside from the method, by implementing onItemClickListener

How to pass ID of one JSON to next Activity?

hello I am new to android in my app i have one ListFragment activity in which i am getting data perfectly where i have list of users now i want that after click on any user i need to show their profile
public class HomeFragment extends ListFragment {
//CustomAdapter adapter;
//private List<RowItem> rowItems;
private ProgressDialog pDialog;
//JSON parser class
JSONParser jsonParser = new JSONParser();
JSONArray matching=null;
ArrayList<HashMap<String,String>> aList;
private static String MATCH_URL = null;
private static final String TAG_MATCH="matching";
private static final String TAG_MATCH_ID="match_detail_id";
private static final String TAG_NAME="name";
private static final String TAG_PROFILE="profile_id";
private static final String TAG_IMAGE="image";
private static final String TAG_CAST="cast";
private static final String TAG_AGE="age";
private static final String TAG_LOCATION="location";
private ListView listview;
String user_match_id;
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("user_login_id");
MATCH_URL = "http://abcd.com/webservice/matching?version=apps&user_login_id="+strtext;
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
aList = new ArrayList<HashMap<String,String>>();
// rowItems = new ArrayList<RowItem>();
listview=(ListView)rootView.findViewById(android.R.id.list);
new LoadAlbums().execute();
return rootView;
}
class LoadAlbums extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(MATCH_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
ArrayList<HashMap<String,String>> listData = new ArrayList<HashMap<String, String>>();
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
matching = jsonObj.getJSONArray(TAG_MATCH);
// looping through All Contacts
for (int i = 0; i < matching.length(); i++) {
JSONObject c = matching.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_MATCH_ID, c.getString(TAG_MATCH_ID));
map.put(TAG_NAME,c.getString(TAG_NAME));
map.put(TAG_PROFILE, c.getString(TAG_PROFILE));
map.put(TAG_IMAGE, c.getString(TAG_IMAGE));
map.put(TAG_CAST, c.getString(TAG_CAST));
map.put(TAG_AGE, c.getString(TAG_AGE)+" years");
map.put(TAG_LOCATION, c.getString(TAG_LOCATION));
// adding HashList to ArrayList
listData.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return listData;
}
protected void onPostExecute( ArrayList<HashMap<String,String>> result) {
super.onPostExecute(result);
// dismiss the dialog after getting all albums
if (pDialog.isShowing())
pDialog.dismiss();
// updating UI from Background Thread
/**
* Updating parsed JSON data into ListView
* */
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Intent intent=new Intent(getActivity(),ProfileEdit.class);
intent.putExtra("match_detail_id", arg2);
startActivity(intent);
}
});
if(aList==null){
aList = new ArrayList<HashMap<String, String>>();
}
aList.addAll(result);
CustomAdapter adapter = new CustomAdapter(getActivity(),aList);
setListAdapter(adapter);
}
}
public class ProfilePage extends Activity{
private ProgressDialog pDialog;
AQuery androidAQuery=new AQuery(this);
//private static final String TAG_MATCH_ID="match_detail_id";
private static final String USER_NAME="name";
private static final String USER_AGE="age";
private static final String USER_LOCATION="location";
private static final String USER_MOTHER_TONGE="mother_tounge";
private static final String USER_OCCU="occupation";
private static final String USER_INCOM="income";
private static final String USER_HEIGHT="height";
private static final String USER_MARRAGE="marital_status";
private static final String USER_RELIGION="religion";
private static final String USER_GOTRA="gotra";
private static final String USER_MANGLIK="manglik";
private static final String USER_RASHI="rashi";
private static final String USER_EDUCATION="education";
private static final String USER_EAT="eating";
private static final String USER_DRINK="drink";
private static final String USER_SMOKE="smoke";
private static final String USER_ABOUT="about_me";
private static final String USER_PIC="profile_pic";
private static String USER_URL="";
String user_match_id;
private ImageView cover;
private ImageView yes;
private ImageView no;
private ImageView sendmsg;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_page);
String matchId=this.getIntent().getStringExtra("match_detail_id");
if(matchId.trim().length()>0){
USER_URL="http://abcds.com/webservice/matchingdetails?version=apps&match_detail_id="+user_match_id;
}else{
Toast.makeText(ProfilePage.this,"match id blank",Toast.LENGTH_LONG).show();
}
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(USER_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String user_name = jsonObj.getString(USER_NAME);
String user_age = jsonObj.getString(USER_AGE);
String user_location = jsonObj.getString(USER_LOCATION);
String user_mothertong = jsonObj.getString(USER_MOTHER_TONGE);
String user_occupation = jsonObj.getString(USER_OCCU);
String user_income = jsonObj.getString(USER_INCOM);
String user_height = jsonObj.getString(USER_HEIGHT);
String user_marg = jsonObj.getString(USER_MARRAGE);
String user_religion = jsonObj.getString(USER_RELIGION);
String user_gotra = jsonObj.getString(USER_GOTRA);
String user_manglik = jsonObj.getString(USER_MANGLIK);
String user_rashi = jsonObj.getString(USER_RASHI);
String user_education = jsonObj.getString(USER_EDUCATION);
String user_eat = jsonObj.getString(USER_EAT);
String user_drink = jsonObj.getString(USER_DRINK);
String user_smoke = jsonObj.getString(USER_SMOKE);
String user_about = jsonObj.getString(USER_ABOUT);
String user_pro = jsonObj.getString(USER_PIC);
final TextView uname = (TextView)findViewById(R.id.namedetail);
final TextView fdetail = (TextView)findViewById(R.id.firstdetail);
final TextView sdetail = (TextView)findViewById(R.id.seconddetail);
final TextView tdetail = (TextView)findViewById(R.id.thirddetail);
final TextView ocdetail=(TextView)findViewById(R.id.txtoccupationdetail);
final TextView incomedetail = (TextView)findViewById(R.id.incomedetaile);
final TextView uheight = (TextView)findViewById(R.id.txtheightprofile);
final TextView umrg = (TextView)findViewById(R.id.txtmrgprofile);
final TextView ureligion = (TextView)findViewById(R.id.prohindu);
final TextView ugotra = (TextView)findViewById(R.id.gothraa);
final TextView umanglik = (TextView)findViewById(R.id.usermanglik);
final TextView urashi = (TextView)findViewById(R.id.rashi);
final TextView udegree = (TextView)findViewById(R.id.userdegree);
final TextView ueat = (TextView)findViewById(R.id.txteatprofile);
final TextView udrink = (TextView)findViewById(R.id.txtdrinkprofile);
final TextView usmoke = (TextView)findViewById(R.id.txtsmokeprofile);
final TextView uabout = (TextView)findViewById(R.id.txtabouther);
final ImageView ucover = (ImageView)findViewById(R.id.coverimage);
uname.setText(user_name);
fdetail.setText(user_age+" years");
sdetail.setText(user_location);
tdetail.setText(user_mothertong);
ocdetail.setText(user_occupation);
incomedetail.setText(user_income);
uheight.setText(user_height);
umrg.setText(user_marg);
ureligion.setText(user_religion);
ugotra.setText(user_gotra);
umanglik.setText(user_manglik);
urashi.setText(user_rashi);
udegree.setText(user_education);
ueat.setText(user_eat);
udrink.setText(user_drink);
usmoke.setText(user_smoke);
uabout.setText(user_about);
androidAQuery.id(ucover).image(user_pro, true, true);
} catch (JSONException e) {
e.printStackTrace();
}
Try to override onListItemClick in fragment :
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Intent intent = new Intent(getActivity(), ProfilePage.class);
intent.putExtra("match_detail_id", aList.get(position).get(TAG_MATCH_ID));
startActivity(intent);
}
Instead of manual setOnItemClickListener to listview so no required this code :
listview=(ListView)rootView.findViewById(android.R.id.list);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
Intent intent=new Intent(getActivity().getApplicationContext(),ProfileEdit.class);
intent.putExtra("position", arg2);
startActivity(intent);
}
});
Note : when you use ListFragment no need to find Listview and set item click as well as setAdapter manually,directly get all method ready like setAdapter() and onListItemClick.
Intent intent = new Intent(getBaseContext(), NewActivity.class);
intent.putExtra("KEY", Value);
startActivity(intent)
Try with below code:
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Intent intent=new Intent(getActivity(),ProfileEdit.class);
intent.putExtra("match_detail_id", arg2);
startActivity(intent);
}
});
//get this data as below in ProfileEdit class
String matchId=this.getIntent().getStringExtra(""match_detail_id"");
if(matchId.trim().length()>0){
USER_URL="http://gujjumatch.com/webservice/matchingdetails?version=apps&match_detail_id="+user_match_id;
}else{
Toast.makeText(ProfileEdit.this,"match id blank",Toast.LENGTH_LONG).show();
}

"returnRes cannot be resolved to a variable" error in android

I had tested the function of endless Scrolling function in a dummy projects, it works fine but if i paste the same code in my original project m getting "loadMoreListItems cannot be resolved to a variable" on the variable "loadMoreListItems" and "returnRes cannot be resolved to a variable" on the variable, even i checked for android.R imports and layout name everything is correct dont know where is the mistake.
public class Home extends ListActivity {
ArrayList<HashMap<String, String>> songsList;
ListView list;
LazyAdapter adapter;
JSONArray posts;
LinearLayout line1,line2;
ImageView menu;
boolean loadingMore = false;
ArrayList<String> songsList1;
LayoutInflater inflater;
static int jsonpage = 0;
JSONParser jParser;
JSONObject json;
TextView loadtext;
// All static variables
static final String URL = "http://www.exm.com/?json=get_recent_posts";
static final String KEY_POSTS = "posts";
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_DATE = "date";
static final String KEY_CONTENT = "content";
static final String KEY_AUTHOR = "author";
static final String KEY_NAME = "name";
static final String KEY_ATTACHMENTS = "attachments";
static final String KEY_SLUG = "slug";
static final String KEY_THUMB_URL = "thumbnail";
static final String KEY_IMAGES = "images";
static final String KEY_URL = "url";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list = (ListView) findViewById(android.R.id.list);
// get the LayoutInflater for inflating the customomView
// this will be used in the custom adapter
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
songsList = new ArrayList<HashMap<String, String>>();
_loaddata();
LayoutInflater li = LayoutInflater.from(getBaseContext());
View footerView = li.inflate(com.exm.com.R.layout.listfooter, null);
loadtext = (TextView) footerView.findViewById(R.id.empty);
loadtext.setEnabled(false);
loadtext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "poda",
Toast.LENGTH_LONG).show();
}
});
this.getListView().addFooterView(footerView);
// Getting adapter by passing json data ArrayList
adapter = new LazyAdapter(this, songsList);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(
getApplicationContext(),
"Click ListItem Number "
+ songsList.get(position).get("title"),
Toast.LENGTH_LONG).show();
}
});
this.getListView().setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// int first = view.getFirstVisiblePosition();
// int count = view.getChildCount();
//
// if (scrollState == SCROLL_STATE_IDLE
// || (first + count > adapter.getCount())) {
// list.invalidateViews();
// }
if (scrollState == SCROLL_STATE_IDLE) {
_loaddata();
adapter.notifyDataSetChanged();
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
});
Thread thread = new Thread(null, loadMoreListItems);
thread.start();
}
#SuppressWarnings("unused")
private void _loaddata() {
try {
// getting JSON string from URL
jParser = new JSONParser();
jsonpage = jsonpage + 1;
json = jParser
.getJSONFromUrl("http://india.exm.net/ads/page/"
+ jsonpage + "/?json=get_recent_posts");
posts = json.getJSONArray(KEY_POSTS);
if (posts.length() > 0) {
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(KEY_ID);
String title = c.getString(KEY_TITLE);
String date = c.getString(KEY_DATE);
String content = c.getString(KEY_CONTENT);
// to remove all <P> </p> and <br /> and replace with ""
content = content.replace("<br />", "");
content = content.replace("<p>", "");
content = content.replace("</p>", "");
// authornumber is agin JSON Object
JSONObject author = c.getJSONObject(KEY_AUTHOR);
String name = author.getString(KEY_NAME);
String url = null;
String slug = null;
try {
JSONArray atta = c.getJSONArray("attachments");
for (int j = 0; j < atta.length(); j++) {
JSONObject d = atta.getJSONObject(j);
slug = d.getString(KEY_SLUG);
JSONObject images = d.getJSONObject(KEY_IMAGES);
JSONObject thumbnail = images
.getJSONObject(KEY_THUMB_URL);
url = thumbnail.getString(KEY_URL);
}
} catch (Exception e) {
e.printStackTrace();
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, id);
map.put(KEY_TITLE, title);
map.put(KEY_DATE, date);
map.put(KEY_NAME, name);
map.put(KEY_CONTENT, content);
map.put(KEY_SLUG, slug);
map.put(KEY_URL,
url);
// adding HashList to ArrayList
songsList.add(map);
}
} else
loadtext.setText("Data ivlo thaan irukku k va summa look-u vidatha");
} catch (JSONException e) {
e.printStackTrace();
}
// Runnable to load the items
Runnable loadMoreListItems = new Runnable() {
#Override
public void run() {
// Set flag so we cant load new items 2 at the same time
loadingMore = true;
// Reset the array that holds the new items
songsList1 = new ArrayList<String>();
// Simulate a delay, delete this on a production environment!
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
runOnUiThread(returnRes);
}
};
// Since we cant update our UI from a thread this Runnable takes care of
// that!
private Runnable returnRes = new Runnable() {
#Override
public void run() {
// Loop thru the new items and add them to the adapter
if (songsList1 != null && songsList1.size() > 0) {
for (int i = 0; i < songsList1.size(); i++)
adapter.add(songsList1.get(i));
}
// Update the Application title
setTitle("Neverending List with "
+ String.valueOf(adapter.getCount()) + " items");
// Tell to the adapter that changes have been made, this will cause
// the list to refresh
adapter.notifyDataSetChanged();
// Done loading more.
loadingMore = false;
}
};
This has nothing to do with Android resources.
The variable loadMoreListItems is used in onCreate(), but it is defined in _loaddata(). You cannot define a variable in one method and use it in another method.
You could return loadMoreListItems from _loaddata()
private Runnable _loaddata() {
...
return loadMoreListItems;
}
and use it in onCreate() like
Runnable loadMoreListItems = _loaddata();
...
Thread thread = new Thread(null, loadMoreListItems);
And you use returnRes in Runnable loadMoreListItems before it is defined later in the same method. You must first define and initialize returnRes and then you can use it in loadMoreListItems. So moving returnRes before loadMoreListItems should solve this one.

Listview becomes empty after giving the keyword in search bar in android

Currently i'm working on How to find the items from the listview when given the keyword for the item in edittext, the listview becomes empty and the output is displaying in toast message, can anybody help like how to make the found "item" to display it in listivew?
public class Home extends ListActivity {
//how many to load on reaching the bottom
int itemsPerPage = 15;
boolean loadingMore = false;
ArrayList<String> songsList;
ListView list;
LazyAdapter adapter, adapter1;
JSONArray posts;
//ArrayList thats going to hold the search results
ArrayList<HashMap<String, String>> searchResults;
LayoutInflater inflater;
// All static variables
static final String URL = "http://abc.net/ads/?json=get_recent_posts";
static final String KEY_POSTS = "posts";
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_DATE = "date";
static final String KEY_CONTENT = "content";
static final String KEY_AUTHOR = "author";
static final String KEY_NAME = "name";
static final String KEY_ATTACHMENTS = "attachments";
static final String KEY_SLUG = "slug";
static final String KEY_THUMB_URL = "thumbnail";
static final String KEY_IMAGES = "images";
static final String KEY_URL = "url";
private static final String DEBUGTAG = null;
protected static final String TAG = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText searchBox=(EditText) findViewById(R.id.search);
final ListView list=(ListView)findViewById(android.R.id.list);
//get the LayoutInflater for inflating the customomView
//this will be used in the custom adapter
inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
final JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
posts = json.getJSONArray(KEY_POSTS);
// looping through all song nodes <song>
for(int i = 0; i < posts.length(); i++){
JSONObject c = posts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(KEY_ID);
String title = c.getString(KEY_TITLE);
String date = c.getString(KEY_DATE);
String content = c.getString(KEY_CONTENT);
// to remove all <P> </p> and <br /> and replace with ""
content = content.replace("<br />", "");
content = content.replace("<p>", "");
content = content.replace("</p>", "");
//authornumber is agin JSON Object
JSONObject author = c.getJSONObject(KEY_AUTHOR);
String name = author.getString(KEY_NAME);
String url = null;
String slug = null;
try {
JSONArray atta = c.getJSONArray("attachments");
for(int j = 0; j < atta.length(); j++){
JSONObject d = atta.getJSONObject(j);
slug = d.getString(KEY_SLUG);
JSONObject images = d.getJSONObject(KEY_IMAGES);
JSONObject thumbnail = images.getJSONObject(KEY_THUMB_URL);
url = thumbnail.getString(KEY_URL);
}
} catch (Exception e) {
e.printStackTrace();
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, id);
map.put(KEY_TITLE, title);
map.put(KEY_DATE, date);
map.put(KEY_NAME, name);
map.put(KEY_CONTENT, content);
map.put(KEY_SLUG, slug);
map.put(KEY_URL, url);
// adding HashList to ArrayList
songsList.add(map);
}
}catch (JSONException e) {
e.printStackTrace();
}
//searchResults=OriginalValues initially
searchResults=new ArrayList<HashMap<String, String>>(songsList);
// Getting adapter by passing json data ArrayList
adapter = new LazyAdapter(this, songsList);
list.setAdapter(adapter);
searchBox.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
//get the text in the EditText
String searchString = searchBox.getText().toString();
int textLength = searchString.length();
//clear the initial data set
searchResults.clear();
for (int i = 0; i < songsList.size(); i++) {
String playerName = songsList.get(i).get("title").toString();
if (textLength <= playerName.length()) {
//compare the String in EditText with Names in the ArrayList
if (searchString.equalsIgnoreCase(playerName.substring(0, textLength)))
Toast.makeText(getApplicationContext(), playerName, 1).show();
Home.this.adapter.getFilter();
searchResults.add(songsList.get(i));
Log.d(TAG, "title");
}
}
adapter.notifyDataSetChanged();
list.setAdapter(new ArrayAdapter<String>
(Home.this,
R.layout.activity_home));
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
Home.this.adapter.getFilter();
}
});
adapter.notifyDataSetChanged();
list.setAdapter(new ArrayAdapter<String>(Home.this, R.layout.activity_home));
You are not giving any data set to populate the ListView.
Just like you initially populated the ListView with songsList data
adapter = new LazyAdapter(this, songsList);
list.setAdapter(adapter);
use:
adapter = new LazyAdapter(this, searchResults);
list.setAdapter(adapter);
try this,
edittext code for search
etSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Call back the Adapter with current character to Filter
adapter1.getFilter().filter(s.toString());
}
........
add arraylist to listview to display
adapter1 = new MyAdapter(MainActivity.this, mProductArrayList);
lvProducts.setAdapter(adapter1);
Adapter Class
public class MyAdapter extends BaseAdapter implements Filterable {
private ArrayList<Product> mOriginalValues; // Original Values
private ArrayList<Product> mDisplayedValues; // Values to be displayed
LayoutInflater inflater;
public MyAdapter(Context context, ArrayList<Product> mProductArrayList) {
this.mOriginalValues = mProductArrayList;
this.mDisplayedValues = mProductArrayList;
inflater = LayoutInflater.from(context);
}
..........
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.row, null);
holder.llContainer = (LinearLayout)convertView.findViewById(R.id.llContainer1);
holder.tvName = (TextView) convertView.findViewById(R.id.tvName);
holder.tvPrice = (TextView) convertView.findViewById(R.id.tvPrice);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvName.setText(mDisplayedValues.get(position).name);
holder.tvPrice.setText(mDisplayedValues.get(position).price+"");
holder.llContainer.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(MainActivity.this, mDisplayedValues.get(position).price.toString() , Toast.LENGTH_SHORT).show();
}
});
return convertView;
}

Categories

Resources