Searching with EditText - android

Can you help me with this. I want to create a search for my listview using editText. Everything is okay but when i run the application it causes a runtime error and i get the an NullPointerException on AlbumActivity.onTextChanged . Any idea how to solve this? Thanks. Here's the code:
#SuppressLint("NewApi")
public class AlbumsActivity extends ListActivity{
ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> albumsList;
JSONArray albums = null;
EditText inputSearch;
ArrayAdapter<String> adapter = null;
private static final String URL_ALBUMS = "http://api.androidhive.info/songs/album.php";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_SONGS_COUNT = "songs_count";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_albums);
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
getActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
cd = new ConnectionDetector(getApplicationContext());
if (!cd.isConnectingToInternet()) {
alert.showAlertDialog(AlbumsActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
return;
}
albumsList = new ArrayList<HashMap<String, String>>();
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
AlbumsActivity.this.adapter.getFilter().filter(cs.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
new LoadAlbums().execute();
ListView lv = getListView();
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
Intent i = new Intent(getApplicationContext(), TrackListActivity.class);
String album_id = ((TextView) view.findViewById(R.id.album_id)).getText().toString();
i.putExtra("album_id", album_id);
startActivity(i);
}
});
}
class LoadAlbums extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AlbumsActivity.this);
pDialog.setMessage("Listing Albums ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
String json = jsonParser.makeHttpRequest(URL_ALBUMS, "GET",
params);
Log.d("Albums JSON: ", "> " + json);
try {
albums = new JSONArray(json);
if (albums != null) {
for (int i = 0; i < albums.length(); i++) {
JSONObject c = albums.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String songs_count = c.getString(TAG_SONGS_COUNT);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_SONGS_COUNT, songs_count);
albumsList.add(map);
}
}else{
Log.d("Albums: ", "null");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
AlbumsActivity.this, albumsList,
R.layout.list_item_albums, new String[] { TAG_ID,
TAG_NAME, TAG_SONGS_COUNT }, new int[] {
R.id.album_id, R.id.album_name, R.id.songs_count });
setListAdapter(adapter);
}
});
}
}
}

Your adapter is not initialized. You make the following call :
AlbumsActivity.this.adapter.getFilter().filter(cs.toString());
This won't work because your adapter is null. You call setListAdapter in onPostExecute but that is a method of ListActivity that uses an internal adapter, it will not initialize your own member variable.
Instead, you could do this in onPostExecute :
AlbumsActivity.this.adapter = new SimpleAdapter(AlbumsActivity.this, albumsList, R.layout.list_item_albums, new String[] { TAG_ID, TAG_NAME, TAG_SONGS_COUNT }, new int[] {R.id.album_id, R.id.album_name, R.id.songs_count });
// updating listview
setListAdapter(AlbumsActivity.this.adapter);

Related

How to Show JSON DATA in LISTVIEW

I have a JSON data from YouTube. I want to show data in LIST VIEW. But when i run my code I get a blank page. But I have the respond of YouTube DATA API. How can I solve it?
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "https://www.googleapis.com/youtube/v3/search?part=snippet&maxResult=30&q=natok+bangla+mosharrof+karim&key=AIzaSyCR40QlsuX0aFfBV-wEPDsH_jxna1tDFRA";
private static final String TAG_ITEMS = "items";
private static final String TAG_ID = "id";
private static final String TAG_ID_VIDEOID = "vid";
private static final String TAG_TITLE = "title";
private static final String TAG_DESCRIPTION = "description";
private static final String YouTubeThumbnail = "https://i.ytimg.com/vi/hlaX2OZ_kDg/default.jpg";
private static final String TAG_CHANNELTITLE = "channelTitle";
JSONArray items = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> dataList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String vid = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String title = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_ID_VIDEOID, vid);
in.putExtra(TAG_TITLE, title);
in.putExtra(TAG_DESCRIPTION, description);
startActivity(in);
}
});
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
ArrayList<HashMap<String, String>> dataList = new ArrayList<HashMap<String,String>>();
int count = 0;
try {
JSONObject js = new JSONObject(jsonStr);
JSONArray jsItem = js.getJSONArray("items");
for (int i = 0; i < jsItem.length(); i++) {
JSONObject item = jsItem.getJSONObject(i);
JSONObject vid =item.getJSONObject("id");
String videoId = getStringResult(vid.toString(), "videoId");
if (!videoId.equalsIgnoreCase(""))
{
JSONObject snippet =item.getJSONObject("snippet");
String title = sh.getStringResult(snippet.toString(), "title");
HashMap<String, String> map = new HashMap<String, String>();
map.put("name", title);
map.put("vid", videoId);
map.put ("img","http://img.youtube.com/vi/" + videoId + "/hqdefault.jpg");
map.put ("id",++count+"");
dataList.add(map);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, dataList,R.layout.list_item, new String[] { TAG_TITLE, TAG_DESCRIPTION,
TAG_CHANNELTITLE }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}
public String getStringResult(String data, String node) {
try {
JSONObject js = new JSONObject(data);
return js.getString(node);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
Use notifyDataSetChanged(). This notifies a change in data and updated the list view. LINK
Here are the changes that would help:
public class MainActivity extends ListActivity {
...
ListAdapter adapter = null;
#Override
public void onCreate(Bundle savedInstanceState) {
...
ListView lv = getListView();
adapter = new SimpleAdapter(
MainActivity.this, dataList,R.layout.list_item, new String[] { TAG_TITLE, TAG_DESCRIPTION,
TAG_CHANNELTITLE }, new int[] { R.id.name,
R.id.email, R.id.mobile });
lv.setListAdapter(adapter);
...
}
private class GetContacts extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
...
}
#Override
protected Boolean doInBackground(Void... arg0) {
...
}
#Override
protected void onPostExecute(Boolean result) {
if(adapter ! = null) {
adapter.notifyDataSetChanged();
}
}
public String getStringResult(String data, String node) {
...
}
Explanation:
ListAdapter is the bridge between a ListView and the data that backs the list.
Whenever the data is changed, adapter is responsible to notify about the changed data and consequently the view gets updated with the new data. This is achieved by notifyDataSetChanged().
For some more details, please go through this link.

How to Listview with image ? Anyone have any idea how to do that using this code

I already try to display image in ListView, but I got an error at this line:
status.setImageResource(R.drawable.inprogress);
*setimageresource undefined for String.
I'm trying to display the image based on the status, if status equals to "Compalint in process" and then the in progress icon will display in the ListView.
This my full code:
public class SenaraiSemuaComplaint extends ListActivity {
String stud_staff_ID;
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> listcomplaint;
final Context context = this;
private static String url_listcomplaint = "...";
private static final String TAG_SUCCESS = "success";
private static final String TAG_REGISTER = "register";
private static final String TAG_PID = "pid";
private static final String TAG_DATE = "date";
private static final String TAG_STATUS = "status";
JSONArray register = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listallcomplaint_layout);
getActionBar().setHomeButtonEnabled(true);
String input = getIntent().getStringExtra("stud_staff_ID");
Toast.makeText(this, input, Toast.LENGTH_SHORT).show();
listcomplaint = new ArrayList<HashMap<String, String>>();
new LoadAllComplaint().execute();
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String pid = ((TextView) view.findViewById(R.id.pid)).getText()
.toString();
String location = ((TextView) view.findViewById(R.id.location)).getText()
.toString();
String picture = ((TextView) view.findViewById(R.id.picture)).getText()
.toString();
String input = getIntent().getStringExtra("stud_staff_ID");
Intent in = new Intent(getApplicationContext(),
ViewPage.class);
in.putExtra("location", location);
in.putExtra("picture", picture);
in.putExtra("stud_staff_ID", input);
in.putExtra("pid", pid);
startActivityForResult(in, 100);
}
});
}
public boolean onOptionsItemSelected(MenuItem item){
if(android.R.id.home == item.getItemId()){
finish();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
class LoadAllComplaint extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SenaraiSemuaComplaint.this);
pDialog.setMessage("Please wait, Loading Data...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
String input = getIntent().getStringExtra("stud_staff_ID");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("input", input));
JSONObject json = jParser.makeHttpRequest(url_listcomplaint, "GET", params);
Log.d("List Complaint: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
register = json.getJSONArray(TAG_REGISTER);
for (int i = 0; i < register.length(); i++) {
JSONObject c = register.getJSONObject(i);
// keep to variable
String pid = c.getString(TAG_PID);
String date = c.getString(TAG_DATE);
String status = c.getString(TAG_STATUS);
if (status.equals("Complaint in process."))
{
status.setImageResource(R.drawable.inprogress);
}
String location = c.getString("location");
String picture = c.getString("picture");
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_PID, pid);
map.put(TAG_DATE, date);
map.put(TAG_STATUS, status);
map.put("location", location);
map.put("picutre", picture);
listcomplaint.add(map);
}
} else {
runOnUiThread(new Runnable()
{
public void run(){
String msgs = "No complaint found, please create new complaint.";
Toast.makeText(getApplicationContext(), msgs, Toast.LENGTH_SHORT).show();
}
});
String i = getIntent().getStringExtra("stud_staff_ID");
Intent in12 = new Intent(getApplicationContext(),ComplaintBaru.class);
in12.putExtra("stud_staff_ID", i);
startActivity(in12);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
SenaraiSemuaComplaint.this, listcomplaint,
R.layout.list_pendaftaran, new String[] {TAG_PID,
TAG_DATE, TAG_STATUS, "location", "picture" },
new int[] {R.id.pid, R.id.inputDate, R.id.inputStatus, R.id.location, R.id.picture});
setListAdapter(adapter);
}
});
}
}
}
I suggest judging by what you want to achieve that handle this in your Adapter for the ListView which would be the adapter you supply to the ListActivity.
In the getView() of your adapter check the value of your TextView and then replace it with a ProgressBar either dynamically or by toggling its visibility by letting it reside in the layout for your rows.
it's require to take ImageView than set to Image
Imageview img=(ImageView)findViewById(R.id.yourimageID).setImageResource(R.drawable.inprogress);

Load page 2,3,4 in AsyncTask from JSON paginated file Android

I have a paginated JSON file where I have all my data. At the end of my url link, if you change the page number, it executes and lists next items like "?page=1" or "3,4,5,6".
By default its kept at "?page=0" which is the first page viewed when parsed in Android.
I have also added a footer view with a Button "LoadMore" which is seen at the end of the listview.
Now I wanted this LoadMore button to go to page 2 after clicking when I am at page 1 end. again to page 3, when I click LoadMore on page 2.
I am so confused of implementing it. This is my Asynic Task. Something to do in "doInBackground"
class LoadRestaurants extends AsyncTask<String, String, String> {
//Show Progress Dialog
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchAll.this);
pDialog.setMessage("Loading All Restaurants...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... arg) {
//building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
current_page = 0;
URL_RESTAURANT_LIST
= "http://www.petuuk.com/android/allRestaurantList3.php?page=" + current_page;
//Getting JSON from URL
String json = jsonParser.makeHttpRequest(URL_RESTAURANT_LIST, "GET", params);
//Log Cat Response Check
Log.d("Areas JSON: ", "> " + json);
try {
restaurants = new JSONArray(json);
if (restaurants != null) {
//loop through all restaurants
for (int i = 0; i < restaurants.length(); i++) {
JSONObject c = restaurants.getJSONObject(i);
//Storing each json object in the variable.
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String location = c.getString(TAG_LOCATION);
String rating = c.getString(TAG_RATING);
//Creating New Hashmap
HashMap<String, String> map = new HashMap<String, String>();
//adding each child node to Hashmap key
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_LOCATION, location);
map.put(TAG_RATING, rating);
//adding HashList to ArrayList
restaurant_list.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
//dismiss the dialog
pDialog.dismiss();
//Updating UI from the Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
ListAdapter adapter = new SimpleAdapter(
SearchAll.this, restaurant_list,
R.layout.listview_restaurants, new String[]{
TAG_ID, TAG_NAME, TAG_LOCATION, TAG_RATING}, new int[]{
R.id.login_id, R.id.restaurant_name, R.id.address, R.id.rating});
setListAdapter(adapter);
ListView lv = getListView();
int currentPosition = lv.getFirstVisiblePosition();
lv.setSelectionFromTop(currentPosition + 1, 1);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Bundle bundle = new Bundle();
Intent intent = new Intent(getApplicationContext(),RestaurantProfile.class);
String loginId = ((TextView) view.findViewById(R.id.login_id)).getText().toString();
String res_name = ((TextView)
view.findViewById(R.id.restaurant_name)).getText().toString();
intent.putExtra(TAG_ID, loginId);
intent.putExtra(TAG_NAME, res_name);
startActivity(intent);
}
});
}
});
}
}
This is my LoadMore Button code.
Button btnLoadMore = new Button(SearchAll.this);
btnLoadMore.setText("Show More");
getListView().addFooterView(btnLoadMore);
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
My searchAll file, where all the code goes.
public class SearchAll extends ListActivity {
ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
//Progress Dialog
private ProgressDialog pDialog;
//make json parser Object
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> restaurant_list;
//Restaurant Json array
JSONArray restaurants = null;
private String URL_RESTAURANT_LIST
= "http://www.petuuk.com/android/allRestaurantList3.php?page=0";
//all JSON Node Names
private static final String TAG_ID = "login_id";
private static final String TAG_NAME = "name";
private static final String TAG_LOCATION = "location";
private static final String TAG_RATING = "rating";
//Flag for current page
int current_page = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_all);
cd = new ConnectionDetector(getApplicationContext());
//Check for Internet Connection
if (!cd.isConnectingToInternet()) {
//Internet connection not present
alert.showAlertDialog(SearchAll.this, "Internet Connection Error",
"Please Check Your Internet Connection", false);
//stop executing code by return
return;
}
restaurant_list = new ArrayList<HashMap<String, String>>();
new LoadRestaurants().execute();
//new LoadRestaurants().execute();
Button btnLoadMore = new Button(SearchAll.this);
btnLoadMore.setText("Show More");
getListView().addFooterView(btnLoadMore);
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new LoadMore().execute();
}
});
}
class LoadRestaurants extends AsyncTask<String, String, String> {
//Show Progress Dialog
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchAll.this);
pDialog.setMessage("Loading All Restaurants...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... arg) {
//building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
URL_RESTAURANT_LIST
= "http://www.petuuk.com/android/allRestaurantList3.php?page=0";
//Getting JSON from URL
String json = jsonParser.makeHttpRequest(URL_RESTAURANT_LIST, "GET", params);
//Log Cat Response Check
Log.d("Areas JSON: ", "> " + json);
try {
restaurants = new JSONArray(json);
if (restaurants != null) {
//loop through all restaurants
for (int i = 0; i < restaurants.length(); i++) {
JSONObject c = restaurants.getJSONObject(i);
//Storing each json object in the variable.
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String location = c.getString(TAG_LOCATION);
String rating = c.getString(TAG_RATING);
//Creating New Hashmap
HashMap<String, String> map = new HashMap<String, String>();
//adding each child node to Hashmap key
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_LOCATION, location);
map.put(TAG_RATING, rating);
//adding HashList to ArrayList
restaurant_list.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
//dismiss the dialog
pDialog.dismiss();
//Updating UI from the Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
ListAdapter adapter = new SimpleAdapter(
SearchAll.this, restaurant_list,
R.layout.listview_restaurants, new String[]{
TAG_ID, TAG_NAME, TAG_LOCATION, TAG_RATING}, new int[]{
R.id.login_id, R.id.restaurant_name, R.id.address, R.id.rating});
setListAdapter(adapter);
ListView lv = getListView();
int currentPosition = lv.getFirstVisiblePosition();
lv.setSelectionFromTop(currentPosition + 1, 1);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Bundle bundle = new Bundle();
Intent intent = new Intent(getApplicationContext(), RestaurantProfile.class);
String loginId = ((TextView) view.findViewById(R.id.login_id)).getText().toString();
String res_name =((TextView) view.findViewById
(R.id.restaurant_name)).
getText().toString();
intent.putExtra(TAG_ID, loginId);
intent.putExtra(TAG_NAME, res_name);
startActivity(intent);
}
});
}
});
}
}
private class LoadMore extends AsyncTask<Void, Void, Void> {
//Show Progress Dialog
#Override
protected Void doInBackground(Void... voids) {
//building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
current_page = current_page + 1;
URL_RESTAURANT_LIST
= "http://www.petuuk.com/android/allRestaurantList3.php?page=" + current_page;
//Getting JSON from URL
String json = jsonParser.makeHttpRequest(URL_RESTAURANT_LIST, "GET", params);
//Log Cat Response Check
Log.d("Areas JSON: ", "> " + json);
try {
restaurants = new JSONArray(json);
if (restaurants != null) {
//loop through all restaurants
for (int i = 0; i < restaurants.length(); i++) {
JSONObject c = restaurants.getJSONObject(i);
//Storing each json object in the variable.
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String location = c.getString(TAG_LOCATION);
String rating = c.getString(TAG_RATING);
//Creating New Hashmap
HashMap<String, String> map = new HashMap<String, String>();
//adding each child node to Hashmap key
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_LOCATION, location);
map.put(TAG_RATING, rating);
//adding HashList to ArrayList
restaurant_list.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void unused) {
// closing progress dialog
pDialog.dismiss();
}
}
}
Finally got it working!
public class SearchAll extends ListActivity {
ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();
//Progress Dialog
private ProgressDialog pDialog;
//make json parser Object
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> restaurant_list;
//Restaurant Json array
JSONArray restaurants = null;
private String URL_RESTAURANT_LIST
= "http://www.petuuk.com/android/allRestaurantList3.php?page=0";
//all JSON Node Names
private static final String TAG_ID = "login_id";
private static final String TAG_NAME = "name";
private static final String TAG_LOCATION = "location";
private static final String TAG_RATING = "rating";
//Flag for current page
// int current_page = 1;
int bCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_all);
cd = new ConnectionDetector(getApplicationContext());
//Check for Internet Connection
if (!cd.isConnectingToInternet()) {
//Internet connection not present
alert.showAlertDialog(SearchAll.this, "Internet Connection Error",
"Please Check Your Internet Connection", false);
//stop executing code by return
return;
}
restaurant_list = new ArrayList<HashMap<String, String>>();
new LoadRestaurants().execute();
//new LoadRestaurants().execute();
Button btnLoadMore = new Button(SearchAll.this);
btnLoadMore.setText("Show More");
getListView().addFooterView(btnLoadMore);
btnLoadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bCount++;
new LoadRestaurants().execute();
}
});
}
class LoadRestaurants extends AsyncTask<String, String, String> {
//Show Progress Dialog
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchAll.this);
pDialog.setMessage("Loading All Restaurants...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... arg) {
//building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
URL_RESTAURANT_LIST
= "http://www.petuuk.com/android /allRestaurantList3.php?page=
" + bCount;
//Getting JSON from URL
String json = jsonParser.makeHttpRequest(URL_RESTAURANT_LIST, "GET", params);
//Log Cat Response Check
Log.d("Areas JSON: ", "> " + json);
try {
restaurants = new JSONArray(json);
if (restaurants != null) {
//loop through all restaurants
for (int i = 0; i < restaurants.length(); i++) {
JSONObject c = restaurants.getJSONObject(i);
//Storing each json object in the variable.
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String location = c.getString(TAG_LOCATION);
String rating = c.getString(TAG_RATING);
//Creating New Hashmap
HashMap<String, String> map = new HashMap<String, String>();
//adding each child node to Hashmap key
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_LOCATION, location);
map.put(TAG_RATING, rating);
//adding HashList to ArrayList
restaurant_list.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
//dismiss the dialog
pDialog.dismiss();
//Updating UI from the Background Thread
runOnUiThread(new Runnable() {
#Override
public void run() {
ListAdapter adapter = new SimpleAdapter(
SearchAll.this, restaurant_list,
R.layout.listview_restaurants, new String[]{
TAG_ID, TAG_NAME, TAG_LOCATION, TAG_RATING}, new int[]{
R.id.login_id, R.id.restaurant_name, R.id.address, R.id.rating});
setListAdapter(adapter);
ListView lv = getListView();
int currentPosition = lv.getFirstVisiblePosition();
lv.setSelectionFromTop(currentPosition + 1, 1);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Bundle bundle = new Bundle();
Intent intent = new Intent(getApplicationContext(), RestaurantProfile.class);
String loginId = ((TextView) view.findViewById(R.id.login_id)).getText().toString();
String res_name = ((TextView) view.findViewById(R.id.restaurant_name))
.getText().toString();
intent.putExtra(TAG_ID, loginId);
intent.putExtra(TAG_NAME, res_name);
startActivity(intent);
}
});
}
});
}
}
}

Handle Scrolling Android

I have used json with my Listview in fragment but it take time because i have 190 object so i want it to show only 15 items of Json and will so 15 more if the user scroll to the end. My json file i got from dropbox the size is 2,3MB. Can any tell me a good suggestion ? Thank in advance.
Here are the code.
public class UniversityFragment extends Fragment implements OnScrollListener{
ListView lv;
private ProgressDialog pDialog;
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_NAME = "name";
private static final String TAG_ADDRESS = "address";
private static final String TAG_CityProvince = "city/province";
private static final String TAG_Country = "country";
private static final String TAG_PHONE_OFFICE = "officephone";
private static final String TAG_Fax = "fax";
private static final String TAG_EMAIL = "email";
private static final String TAG_Site = "site";
private static final String TAG_image = "image";
int textlength = 0;
// contacts JSONArray
JSONArray contacts = null;
JSONObject jsonobject;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
// Search EditText
EditText inputSearch;
public UniversityFragment() {
}
#SuppressLint("CutPasteId")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_university,
container, false);
// Execute DownloadJSON AsyncTask
contactList = new ArrayList<HashMap<String, String>>();
lv = (ListView) rootView.findViewById(R.id.listView1);
inputSearch = (EditText) rootView.findViewById(R.id.inputSearch);
lv.setTextFilterEnabled(true);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int start, int before,
int count) {
// TODO Auto-generated method stub
// When user changed the Text
// UniversityFragment.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence cs, int start,
int count, int after) {
// TODO Auto-generated method stub
try {
// ((Filterable)
// UniversityFragment.this.contacts).getFilter().filter(cs);
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(getActivity(), "" + e, Toast.LENGTH_SHORT)
.show();
}
// lv.setTextFilterEnabled(true);
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(), "Clicked" + position,
Toast.LENGTH_LONG).show();
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cp = ((TextView) view.findViewById(R.id.CPt)).getText()
.toString();
String country = ((TextView) view.findViewById(R.id.countryt))
.getText().toString();
String fax = ((TextView) view.findViewById(R.id.faxt))
.getText().toString();
String site = ((TextView) view.findViewById(R.id.sitet))
.getText().toString();
String email = ((TextView) view.findViewById(R.id.emailt))
.getText().toString();
String phone = ((TextView) view.findViewById(R.id.phonet))
.getText().toString();
String address = ((TextView) view.findViewById(R.id.addresst))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getActivity(), SingleListItem.class);
in.putExtra("email", email);
in.putExtra("city/province", cp);
in.putExtra("country", country);
in.putExtra("fax", fax);
in.putExtra("site", site);
in.putExtra("name", name);
in.putExtra("officephone", phone);
in.putExtra("address", address);enter code here
startActivity(in);
}
});
lv.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
if (firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount!=0) {
}
}
});
// Calling async task to get json
new GetContacts().execute();
return rootView;
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setTitle("Loading");
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// Create an array
contactList = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
String url = "https://dl.dropbox.com........";
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
enter code here
// Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String name = c.getString(TAG_NAME);
String address = c.getString(TAG_ADDRESS);
String country = c.getString(TAG_Country);
String cityprovince = c.getString(TAG_CityProvince);
String officephone = c.getString(TAG_PHONE_OFFICE);
String fax = c.getString(TAG_Fax);
String email = c.getString(TAG_EMAIL);
String site = c.getString(TAG_Site);
// // Phone node is JSON Object
// JSONObject phone = c.getJSONObject(TAG_PHONE);
// String home = phone.getString(TAG_PHONE_HOME);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_NAME, name);
contact.put(TAG_ADDRESS, address);
contact.put(TAG_CityProvince, cityprovince);
contact.put(TAG_Country, country);
contact.put(TAG_PHONE_OFFICE, officephone);
contact.put(TAG_EMAIL, email);
contact.put(TAG_Site, site);
contact.put(TAG_Fax, fax);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
Toast.makeText(getActivity(), "Thank for your patience", Toast.LENGTH_LONG).show();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(getActivity(), contactList,
R.layout.listsingleitem, new String[] { TAG_NAME,
TAG_ADDRESS, TAG_CityProvince, TAG_Country,
TAG_PHONE_OFFICE, TAG_Fax, TAG_EMAIL, TAG_Site },
new int[] { R.id.name, R.id.addresst, R.id.CPt,
R.id.countryt, R.id.phonet, R.id.faxt, R.id.emailt,
R.id.sitet });
adapter.notify();
//adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
}
}
You need to implement an endless adapter (custom listview adapter) to support loading and displaying concurrently.
See this tutorial: http://www.survivingwithandroid.com/2013/10/android-listview-endless-adapter.html

Adding new item on top of listview

When i insert my parsed data into the listview, the added items appear at the bottom i want to put them on top like on facebook new posts are added on top. here is my code:
I am retrieving my comments from a server. Pls help me out
This is the Readpost.java
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.newsfeed);
}
#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(Readpost.this, Addpost.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);
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();
}
}
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.singlepost, 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.scrollTo(0, 0);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
And this is the Addpost.java
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.addpost);
title = (EditText)findViewById(R.id.title);
message = (EditText)findViewById(R.id.message);
mSubmit = (Button)findViewById(R.id.submit);
mSubmit.setOnClickListener(this);
}
#Override
public void onClick(View v) {
new PostComment().execute();
}
class PostComment extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Addpost.this);
pDialog.setMessage("Posting...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String post_title = title.getText().toString();
String post_message = message.getText().toString();
try {
final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String value =(mSharedPreference.getString("username", "anon"));
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", value));
params.add(new BasicNameValuePair("title", post_title));
params.add(new BasicNameValuePair("message", post_message));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(
POST_COMMENT_URL, "POST", params);
Log.d("Post Comment attempt", json.toString());
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Comment Added!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Comment Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Addpost.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
Assuming you retain your ListAdapter as follows:
ListAdapter mAdapter;
You can add a new item like this.
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, "New Title");
map.put(TAG_MESSAGE, "new content");
map.put(TAG_USERNAME, "someone");
mCommentList.add(0, map);
mAdapter.notifyDatasetChanged();
Use this:
mCommentList.add(0, obj);
listAdapter.notifyDataSetChanged();
listView.scrollTo(0, 0);

Categories

Resources