Fatal exception caused by android.os.NetworkOnMainThreadException - java

As I am a beginner to Android programming, I was trying to run some tutorials, but upon running the programs( the source code is available here: http://www.androidhive.info/2012/01/android-json-parsing-tutorial/ ) I got an error.
The program is supposed to read in data from a website and process it, but I think there is something wrong with the networking part.
I am fully aware there have been similar questions here on SO, yet I had no clue how to solve it, perhaps anyone could give solutions which I also can understand.
Strange NetworkOnMainThreadException in Android app?
This is a questions which was asked earlier and is identical to my problem, but I had no clue what they are trying to say there, i.e. "To fix you just need to move any thing that is touching the network to its own thread." makes no sense to me whatsoever..
Can anyone please shed some light on this?

Use an AsyncTask to move your network operation off of the main/ui thread and onto a background/worker thread.
Expanding on the example from the tutorial, wrap the JSON stuff inside of an anonymous AsyncTask:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new AsyncTask<Void, Void, JSONObject>() {
protected JSONObject doInBackground(Void... args) {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
return jParser.getJSONFromUrl(url);
}
protected void onPostExecute(JSONObject json) {
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
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();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_NAME, TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] {
R.id.name, R.id.email, R.id.mobile });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
}
}.execute((Void) null);
}

Related

How to fill ListView with Adapters

I'm aware that this is very simple question but I'm a newbie in Android development so please go easy on me.
Problem that I have is in one of the fragments (AsyncTask specifically) that lays in my main activity.
AsyncTask sends out data to php script which then returns according data in json format. This is then processed and saved to jsonlist array. Up until post execute everything works fine data is downloaded, processed etc. However when program reaches post execute problems start to pop out. And basically i'm unable to list out all the data from jsonlist to listview
//setting up an array
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
//creating list view variable
ListView listview;
//Define work in progress dialog
private ProgressDialog mProgressDialog;
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle("Please wait");
// Set progressdialog message
mProgressDialog.setMessage("Fetching data...");
mProgressDialog.setIndeterminate(false);
}
#Override
protected Boolean doInBackground(String... params) {
//To do in the background
//Define variable of JSON parser type
JSONParser jParser = new JSONParser();
//Pass url to json parser class to fetch and save it into array variable
JSONArray json = jParser.getJSONFromUrl(url);
//loop from 0 to length of an array by increasing by 1
for (int i = 0; i < json.length(); i++) {
//Try and catch routine to prevent any crashes
try {
//Get an object defined in { ... } in original json file
JSONObject c = json.getJSONObject(i);
//Separate object by obtaining values for each of the sections
String vtitle = c.getString(title);
String vcontent = c.getString(content);
String vuser = c.getString(user);
HashMap<String, String> map = new HashMap<String, String>();
//Fill up an array with data extracted
map.put(title, vtitle);
map.put(content, vcontent);
map.put(user, vuser);
//Add values into jsonlist
jsonlist.add(map);
} catch (JSONException e)
{
//In case of any error Stack trace will be returned
e.printStackTrace();
}
}
//Once everything has been done return null value
return null;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
//Insert all data downloaded through list adapter
ListAdapter adapter = new SimpleAdapter(getActivity(), jsonlist, R.layout.list_activity, new String[] { title, content, user }, new int[] { R.id.title, R.id.content, R.id.user });
// Locate the listview
//listview = (ListView) findViewById(R.id.list);
// Set the adapter to the ListView
//listview.setAdapter(adapter);
//Get rid off dialog when operation of fetching data has been done
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
}
As you can see i have tried the commented code but listview = (ListView) findViewById(R.id.list); returns following error:
Cannot resolve method findViewById(int)
which prevents me from executing program. This is very upsetting because I literally have all the data i need in an array but only one line of code stops me from displaying it.
I have also tried:
ListAdapter adapter = new SimpleAdapter(context, jsonlist, R.layout.list_activity, new String[] { title, content, user }, new int[] { R.id.title, R.id.content, R.id.user });
setListAdapter(adapter);
lv = getListView();
But as in previous case error of unresolved method is returned. Which is due to the fact that fragment is extended by fragment and adding anything to it crashes it
public class Fragment2 extends Fragment, ListActivity {...}
Add this to your code in Fragment2 class.
private ListView listview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.YOUR_FRAGMENT_LAYOUT, container, false);
listview = (ListView) v.findViewById(R.id.R.id.list);
return v;
}
Since you are in a Fragment you have to call getView() before findViewById, like this
//Insert all data downloaded through list adapter
ListAdapter adapter = new SimpleAdapter(getActivity(), jsonlist, R.layout.list_activity, new String[] { title, content, user }, new int[] { R.id.title, R.id.content, R.id.user });
// Locate the listview
listview = (ListView) getView().findViewById(R.id.list);

How to filter database output? (android PHP)

I am building an mobile app in where a user logs in and it outputs the contents of my database table which is named "announcements".
What I'm trying to do is to filter out these output based on the "department" column from the "accounts" table in which the users are stored.
The "announcements" table has the column named "receiver".
The contents will only show if the "department" column of the user logged in has the same value as the "receiver column" of the "announcements" column or if the value of the receiver is "all".
How do I do this?
My PHP script
<?php
$host="localhost"; //replace with database hostname
$username="root"; //replace with database username
$password=""; //replace with database password
$db_name="sunshinedb"; //replace with database name
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select * from announcement";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['services'][]=$row;
}
}
mysql_close($con);
echo json_encode($json);
?>
Java class
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ArrayList<HashMap<String, String>> arraylist;
ProgressDialog mProgressDialog;
JSONParser jsonParser = new JSONParser();
String email;
String[] services;
private String url = "http://10.0.3.2/sunshine-ems/services.php";
String user_id;
// ALL JSON node names
private static final String TAG_TRANS_ID = "announcement_id";
private static final String TAG_DATE = "date";
private static final String TAG_SERVICES = "title";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videos_layout);
// get listview
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(),
Single_List.class);
String transaction_id = ((TextView) view
.findViewById(R.id.transac_id)).getText().toString();
i.putExtra("announcement_id", transaction_id);
startActivity(i);
}
});
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(VideosActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading Services");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
JSONObject json = JSONfunctions.getJSONfromURL(url);
// Check your log cat for JSON reponse
Log.d("Service history ", json.toString());
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
try {
// Locate the array name
jsonarray = json.getJSONArray("services");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
json = jsonarray.getJSONObject(i);
String transac_id = json.getString(TAG_TRANS_ID);
String date = json.getString(TAG_DATE);
String service = json.getString(TAG_SERVICES);
// Retrive JSON Objects
map.put(TAG_SERVICES, service);
map.put(TAG_DATE, date);
map.put(TAG_TRANS_ID, transac_id);
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String file_url) {
mProgressDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
VideosActivity.this, arraylist,
R.layout.listview_services, new String[] {
TAG_TRANS_ID, TAG_SERVICES, TAG_DATE },
new int[] { R.id.transac_id, R.id.txt_service,
R.id.txt_date });
// updating listview
setListAdapter(adapter);
}
});
}
}
You are not making any filtering anywhere in your code...
The steps to do it should be these ones (in this order) :
Android side : Calling your webservice (PHP code) with the user's department (in GET or POST parameter)
WS side : Requesting your database with something like SELECT * FROM announcement WHERE receiver = '<department'> OR receiver = 'ALL' where department is the user's department
WS side : Construct the JSON response
Android side : Process the JSON response to display results
The advantages of making it like this :
Limit the number of data transfered (limit network consumption on the Android device and you limit the load on your PHP server)
Limit the number of data processed Android side (limit the load of the Android app : it's not a desktop app ! Never forgive it !)
PS : reading your post and your comment, I really think you should look into these points before starting to make your app : SQL request, PHP MySQL access (as pointed out by #Jay Blanchard), Web services and HTTP protocol, Android AsyncTask

USING collections in Android

I was looking at this code while surfing through Stackoverflow
CODE::
public class MainActivity extends Activity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
static String TYPE = "country";
static String DISTANCE = "distance";
static String RATING = "rating";
static String FLAG = "flag";
static String PRICE= "price";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
//mProgressDialog.setTitle("Fetching the information");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("--------------URL----------");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("ARRAY");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put(MainActivity.NAME, jsonobject.getString("collegeNAME"));
map.put(MainActivity.TYPE, jsonobject.getString("collegeTYPE"));
map.put(MainActivity.FLAG, jsonobject.getString("collegeIMAGE"));
map.put(MainActivity.DISTANCE, jsonobject.getString("collegeDISTANCE"));
map.put(MainActivity.RATING, jsonobject.getString("collegeRATING"));
map.put(MainActivity.PRICE, jsonobject.getString("collegePrice"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
My Question is Why we use collection in android ?
What is the use ?
Why a hashmap is added to ArrayList in the above code ?
Can't we directly set views in android without collection,( I tried
it dosent work when dealing with group of key,value pairs)
.
~ I am a newbie so please go easy on with answers to my questions
I'm not sure how to answer your first 2 questions about collections... but I'll give it a shot.
1, 2) Collections are good for keeping groups of information lumped together and accessible through 1 variable. They also make it very easy to iterate over them, which makes them ideal for things like ListView adapters since that is also a list (or a collection).
Consider the following if you dont have an array
String var1 = "hi1";
String var2 = "hi2";
String var3 = "hi3";
String var4 = "hi4";
String var5 = "hi5";
String var6 = "hi6";
String var7 = "hi7";
String var8 = "hi8";
String var9 = "hi9";
// do something with the variables
Toast.makeText(this, var1, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var2, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var3, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var4, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var5, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var6, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var7, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var8, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var9, Toast.LENGTH_SHORT).show();
Now consider this, if you have arrays:
ArrayList<String> vars = new ArrayList<String(9);
for (int i = 1; i <= 9; i++)
{
vars.add("hi" + i);
Toast.makeText(this, vars.get(i), Toast.LENGTH_SHORT).show();
}
Much, much easier to work with.
3) The Hashmap is added to the array because the author wanted to keep a collection of separate name/value pairs. You can't have multiple keys with the same value in a Hashmap, so if you want that then you have to make a new Hashmap. The adding them to an array was to keep it neat, and then allowed the author to pass the array to a ListView adapter for displaying the values to the user using Android's built-in mechanism.
Basically the author created this Hierarchy:
item1
name
type
flag
distance
rating
price
item2
name
type
flag
distance
rating
price
item3
name
type
flag
distance
rating
price
...etc...
So when the ListView iterated over the array, each separate collection of hashmap values will be available to a new listview item for displaying.
4) You can set values directly, but working with adapters in ListViews makes it much less of a chore. You create an array, pass the array to the listview, and bada-bing-bada-boom, there's your list. Otherwise you will be creating ListView items and setting the display text all yourself for each item. In a similar way to why collections are useful when you have many variables of the same type, passing that collection to a ListView makes it much, much easier to code, maintain, and troubleshoot, not to mention that it just works!
I hope this helps! We are all beginners once :)
This piece of code will go populate an ListView, there are several ways to do that. I believe in this case, the coder is SimpleAdapter http://developer.android.com/reference/android/widget/SimpleAdapter.html.
Some think like:
// In This case the value os NAME is shown on android.R.id.text1 (TextView)
// and PRICE is shown on android.R.id.text2 (TextView)
String[] from = new String[]{MainActivity.NAME, MainActivity.PRICE}; // Map keys
int[] to = new int[]{android.R.id.text1, android.R.id.text2}; // List Layout item views
SimpleAdapter adapter = new SimpleAdapter(context, arraylist, android.R.layout.simple_list_item_2, String[] from, int[] to);
listview.setAdapter(adapter);

Android listview adapter get item id without setting it

I'm new to Android and I have Adapter - ListView model to display array.
I set it's value's so:
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.bank_list,
new String[] { TAG_NAME, TAG_central_office_address }, new int[] {
R.id.bank_name, R.id.central_office_address});
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, android.view.View view,
int position, long id) {
Intent in = new Intent(getApplicationContext(), BankExchangersListActivity.class);
in.putExtra("Bank_id", TAG_ID);
startActivity(in);
}
});
I get my values from JSON:
url = "http://192.168.1.4:3000/banks.json";
// 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
banks = json.getJSONArray(TAG_BANKS);
// looping through All Contacts
for(int i = 0; i < banks.length(); i++){
JSONObject c = banks.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String central_office_address = c.getString(TAG_central_office_address);
// Phone number is agin JSON Object
// 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_central_office_address, name);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
As you can see in JSON I have ID field, but i didn't set it in ListView. For next query I click on ListView element and go to other activity, but I need to get TAG_ID of this element. Maybe I did something wrong? How to get element's TAG_ID on which I click, without displaying it on ListView?
JUST send tag_id of clicked item!
The position parameter of the onItemClick method gives the index of the selected item in the adapted list. So you can find the TAG_ID of the original item at
((Map<String, String>) adapter.getItem(position)).get(TAG_ID)
make the adapter final so that you can reference it inside the listener:
final ListAdapter adapter = ...
Hope this helps you.
you can get Postion of ListSelectedItemId and passed it with Intentand get it in SecondActivity now Here get FirstActivity HashMap with define it static
now use foreachloop to get all values from HashMap like
public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
}
}
now with specific position of ListSelectedItemId you can get values from currentList
or like
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// ...
}

How to use intent to call the method of next activity in android

What i am doing now is--> i'm getting data from the webservice in one activity and displaying the entire data in a listview. i added just a search functinality on the presented listview itself.
My requirement is --> i should have a search button in the first activity. When it is clicked, should show the related result in second activity, to do this added putExtras in the intent like this intent.putExtra("search", searchBox); that is the second activities search function keyword. but still m not getting the searched output.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
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);
// System.out.println("the map is title "+map.get("title"));
//title2.add(map.get("title"));
// 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
searchString=searchBox.getText().toString();
textLength=searchString.length();
searchResults.clear();
for(int i=0;i<songsList.size();i++)
{
playerName=songsList.get(i).get("title").toString();
System.out.println("player name "+playerName);
if(textLength<=playerName.length()){
//compare the String in EditText with Names in the ArrayList
if(searchString.equalsIgnoreCase(playerName.substring(0,textLength))){
searchResults.add(songsList.get(i));
System.out.println("the array list is "+songsList.get(i));
adapter=new LazyAdapter(Home.this, searchResults);
list.setAdapter(adapter);
}
}
Intents are for activity and not methods inside them , So you cannot use it to call any specific method however you can use extras to figure out what you want to do \
like after when you get extras from Intent you can ,
if extras has "search" value
then do something about it

Categories

Resources