JSON data search and bundle in Android - android

Sorry for my bad English.I am new android.
I have some problem for JSON in Android that
(1.)I've been to obtain information from the Internet (JSON). How can I mark all station on googlemap on particular page?
(2.1) I've been to obtain information from the Internet(JSON) and show those information in the listView. This listView is composed by two TextView(txtV1, txtV2). How can I Use the keyword_search to filter the ListView by the editText?
(2.2) If I click the option, the relevant information will be transmitted to the next page and display. Now, I can only bunndle the String data. How can I bundle the (lat,lng) and mark on google map?
This is json :
{
"retCode": "1",
"retVal": [
{
"iid": "339",
"sno": "0001",
"mday": "20140711003603",
"lat": "25.0408578889",
"lng": "121.567904444"
},
{
"iid": "340",
"sno": "0002",
"mday": "20140711003508",
"lat": "25.041",
"lng": "121.556945"
}
]
}
This is problem(2.1) code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.station);
oslist = new ArrayList<HashMap<String, String>>();
new JSONParse().execute();
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
sna = (TextView) findViewById(R.id.sna);
ar = (TextView) findViewById(R.id.ar);
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
youbike = json.getJSONArray(TAG_retVal);
for (int i = 0; i < youbike.length(); i++) {
JSONObject c = youbike.getJSONObject(i);
// Storing JSON item in a Variable
final String iid = c.getString(TAG_iid);
final String sno = c.getString(TAG_sno);
final String mday = c.getString(TAG_mday);
final String lat = c.getString(TAG_lat);
final String lng = c.getString(TAG_lng);
// Adding value HashMap key => value
final HashMap<String, String> map = new HashMap<String, String>();
map.clear();
map.put(TAG_iid, iid);
map.put(TAG_sno, sno);
map.put(TAG_mday, mday);
map.put(TAG_lat, lat);
map.put(TAG_lng, lng);
oslist.add(map);
list = (ListView) findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(station.this,
oslist, R.layout.station_list, new String[] {
TAG_iid, TAG_sno }, new int[] { R.id.sno,
R.id.iid });
list.setAdapter(adapter);
// bundle to next page
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
Intent intent = new Intent();
intent.setClass(station.this, station_1.class);
Bundle b = new Bundle();
b.putString("TAG_iid",
oslist.get(+position).get("iid"));
b.putString("TAG_sno",
oslist.get(+position).get("sno"));
b.putString("TAG_mday",
oslist.get(+position).get("mday"));
b.putString("TAG_lat",
oslist.get(+position).get("lat"));
b.putString("TAG_lng",
oslist.get(+position).get("lng"));
intent.putExtras(b);
startActivity(intent);
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}

To filter your results, take a look at SimpleAdapter#getFilter(). Example:
private void filterResults(CharSequence filterText){
Filter filter = mSimpleAdapter.getFilter();
filter.filter(filterText);
}
...
mSearchBox.addTextChangeListener(new TextWatcher(){
...
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
filterResults(s);
}
});
To pass lat/long trough Bundle, either parse them when taking from JSON by calling JSONObject#getLong or parse them in other Activity with Long#parseLong

It seems that you are trying to parse the data from Taipei city's Youbike service on the Android platform. I wrote such piece of code already, and it's open source (License AGPL).
You might want to take a look at my source code and find out how to do:
https://github.com/le-moulin-studio/bike-friend/blob/master/android/src/main/java/com/lemoulinstudio/bikefriend/ubike/YouBikeStationProvider.java

Related

How to parse item object other activity when click listview?

This is my JSON:
{
"NEWS": [
{
"ID": 1,
"Title": "A",
"News": "A"
},
{
"ID": 2,
"Title": "B",
"News": "B"
}
]
}
I am parsing this JSON in a listview and just showing the Title. Now, If I click on listview item, say, I clicked "A", I want to populate Title and News in other activity. How can i constraint them?
ArrayList<HashMap<String, String>> newList ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
newList = new ArrayList<>();
String items = String.valueOf(newList);
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray NEWS= jsonObj.getJSONArray("NEWS");
for (int i = 0; i < NEWS.length(); i++) {
JSONObject c = icerik.getJSONObject(i);
String ID= c.getString("ID");
String Title= c.getString("Title");
String News= c.getString("News");
HashMap<String, String> newss= new HashMap<>();
newss.put("ID", ID);
newss.put("Title", Title);
newss.put("News", News);
newList.add(newss);
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
final ListAdapter adapter = new SimpleAdapter(
news.this, newList,
R.layout.new_list, new String[]{"Title"},
new int[]{
R.id.Ttile});
lv.setAdapter(adapter);
lv.setClickable(true);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position >= 0)
{
//Intent myIntent = new Intent(view.getContext(), MYSECONDACTIVTY.class);
//startActivityForResult(myIntent, 0);
}
I found it, and tried but it doesn't work. I just want to show item details on other activity when I click on list item.
insert your data to Bundle, Bundle to Intent
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent myIntent = new Intent(view.getContext(), MYSECONDACTIVTY.class);
Bundle myBundle = new Bundle();
myBundle.putString("title", newList.get(postiyion).get("Title");
myBundle.putString("id", newList.get(postiyion).get("ID");
myBundle.putString("news", newList.get(postiyion).get("News");
myIntent.putExtras(mByundle);
startActivityForResult(myIntent, 0);
}
recover these values in MYSECONDACTIVTY e.g. inside onCreate or wherever you need them
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
String title = getIntent().getExtras().getString("Title");
String id = getIntent().getExtras().getString("ID");
String news = getIntent().getExtras().getString("News")
}
this must work! also check this SO question for more details about Bundle and passing to another Activity

How to pass json data in another activity [duplicate]

This question already has answers here:
Passing JSONObject into another activity
(7 answers)
Closed 6 years ago.
public class MainActivity extends **strong text**
AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> companyList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
companyList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list_row_xml);
new GetCompany().execute();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent i = new Intent(MainActivity.this, SingleView.class);
i.putExtra("venue", venue);
startActivity(i);
}
});
}
private class GetCompany extends AsyncTask<Void, Void, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(MainActivity.this,"Json Data is downloading",Toast.LENGTH_LONG).show();
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected JSONObject doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String url = "http://10.0.2.2:6060/api/v1/company/getInfo?limit=10&page=1";
JSONArray company = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + company);
if (company != null) {
try {
// JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
//JSONArray company = new JSONArray(jsonStr);
// System.out.println("Reached");
// looping through All Contacts
for (int i = 0; i < company.length(); i++) {
//System.out.println("Reached1");
JSONObject c = company.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("companyName");
// Walking Details in Json object
JSONObject walkingDetails=c.getJSONObject("walkingdetails");
String date = walkingDetails.getString("walkingdate");
String venue = walkingDetails.getString("venu");
// tmp hash map for single contact
HashMap<String, String> companyy = new HashMap<>();
// adding each child node to HashMap key => value
companyy.put("id",id);
companyy.put("date", date);
companyy.put("companyname", name);
companyy.put("venue", venue);
// adding contact to contact list
companyList.add(companyy);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Json parsing error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errors!", Toast.LENGTH_LONG).show();
}
});
}
return null;
}
/* #Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, companyList,
R.layout.list_row, new String[]{"date","companyname","venue"}, new int[]{ R.id.date, R.id.companyname, venue});
lv.setAdapter(adapter);*/
}
}
second acivity:
public class SingleView extends AppCompatActivity {
EditText txtVenue;
// String[] Venue;
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_view);
Intent i = getIntent();
position = i.getExtras().getInt("positi`enter code here`on");
txtVenue = (EditText) findViewById(R.id.Venue);
}
}
You can not pass directly JSONObject to another activity. But you can convert json to string and pass it. Then in SecondActivity you can convert it to json again.
Start SecondActivity codes in FirstActivity:
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("data", json.toString());
startActivity(intent);
Then get this data from SecondActivity:
String data = getIntent().getStringExtra("data");
try {
JSONObject json = new JSONObject(data);
} catch (JSONException e) {
e.printStackTrace();
}
Good luck.
You can achieve by creating your own class by extending the JSONObject and implementing Serializable interface. So that you can pass through the intent.
You have 2 options:
1. Convert json to string and pass as string.
2. Make model class for json , make it parcelable. Pass this object to next activity.
HashMaps do not preserve ordering.
Better use a model class, it would also be easy to retrieve data.
public class CompanyData {
public String id;
public String date;
public String name;
public String venue;
}
then change arraylist,
ArrayList<CompanyData> companyList;
then store values,
CompanyData companyy = new CompanyData();
companyy.id = id;
companyy.date = date;
companyy.name = name;
companyy.venue = venue;
companyList.add(companyy);
then implement onitemclicklistener,
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
CompanyData data = companyList.get(position);
Intent i = new Intent(MainActivity.this, SingleView.class);
i.putExtra("venue", data.venue);
startActivity(i);
}
});
***To get position simply send position value inside onItemClickListener
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
CompanyData data = companyList.get(position);
Intent i = new Intent(MainActivity.this, SingleView.class);
i.putExtra("position", position);
startActivity(i);
}
});
You can also send all data of a specific position by
CompanyData data = companyList.get(position);
i.putExtra("data", data); //this will pass all data of clicked row

how to extract integer value on textview to another integer inside listview onclicklistener

I working on an Android project which has a ListView and contains one TextView to display the contact and contact are stored in my website in form of json.
json link for contacts
I am able to parse the contacts I have no problem with that. But the problem is the parsed data is displayed as a number like "776057619" in the TextView and I want this TextView number to be taken and stored in a separate variable. By doing this I can use it to prompt the user "weather you want to call that particular number"??. But I don't no how to pull that number from the TextView to a separate variable and use to call inside ListView's OnItemClickListener
below is my code
public class Contactmedia extends ListActivity {
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String READ_CONTACT_URL = "http://www.iamnotcrazy.hol.es/webservice/contact.php";
private static final String TAG_NUMBER ="number";
private static final String TAG_POSTS = "posts";
private JSONArray mid = null;
//manages all of our comments in a list.
private ArrayList<HashMap<String, String>> mContactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contactmedialist);
}
#Override
protected void onResume() {
super.onResume();
new LoadComments().execute();
}
/**
* Retrieves json data of comments
*/
public void updateJSONdata() {
mContactList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_CONTACT_URL);
try {
mid= json.getJSONArray(TAG_POSTS);
for (int i = 0; i < mid.length(); i++) {
JSONObject c = mid.getJSONObject(i);
String number = c.getString(TAG_NUMBER);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_NUMBER, number);
mContactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Inserts the parsed data into our listview
*/
private void updateList() {
ListAdapter adapter = new SimpleAdapter(this, mContactList,
R.layout.contactmediadesign, new String[] { TAG_NUMBER
}, new int[] { R.id.contactno
});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
/* this is where i have problem how to get that number without converting to string*/
TextView v = (TextView)view.findViewById(R.id.contactno);
int myNum = Integer.parseInt(v.getText().toString());
/* and here i want use that mynum after getiing phonenumber for calling purpouse ass shown below
* but its not working :(*/
if (position == 0){
Toast.makeText(getApplicationContext(), "yes you done it!!", Toast.LENGTH_SHORT).show();
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+"myNum"));
startActivity(callIntent);
}
}
});
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Contactmedia.this);
pDialog.setMessage("Loading complaints...");
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();
}
}
}
Since you actually need string, you don't have to convert to integer at all:
TextView v = (TextView)view.findViewById(R.id.contactno);
...
callIntent.setData(Uri.parse("tel:"+ v.getText().toString()));
or if you do need to store that number in variable for some reason, you should use String instead
TextView v = (TextView)view.findViewById(R.id.contactno);
string myNum = v.getText().toString();
...
callIntent.setData(Uri.parse("tel:" + myNum));
I would recommend getting the data associated with that position rather than trying to parse the view to get it.
You can get the data from the adapter with adapter.getItem(int pos). Just make adapter final or a member variable to access it in the OnItemClickListener.
First of all you should check your Manifest file, you should have this outside the "application" tag but within the "manifest" tag:
<uses-permission android:name="android.permission.CALL_PHONE" />
Try to do something like this in your code:
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + v.getText().toString()));
startActivity(callIntent);
You should use String value instead of int
remove the double quotation on mynum. you can also use basic oop to save your integer value. fyi, myNum doesnt have to be an integer. it can be a string
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
/* this is where i have problem how to get that number without converting to string*/
TextView v = (TextView)view.findViewById(R.id.contactno);
int myNum = Integer.parseInt(v.getText().toString());
setNumber(myNum); //saving the myNum variable
System.out.println("number is: " + getNumber());//if you want to get the value of myNum, just call the getNumber()
if (position == 0){
Toast.makeText(getApplicationContext(), "yes you done it!!", Toast.LENGTH_SHORT).show();
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:"+ myNum));//remove the quotation for myNum
startActivity(callIntent);
}
}
private int number;
void setNumber(int number){
this.number=number;
}
int getNumber(){
return number;
}

How to use listview from different xml layout file

I am working on android ListView and i am getting one issue.I created one list view into the XML file installation.xml and i want to use that list view into my Searchdata.java. so basically what i want that when i click on searchdata button than data is fetched from web service and after parsing, it will saved into the listview.and when i click on Installation View button than new window will be appear where i could see that list data.
SearchData.java
public class SearchData extends Activity {
EditText Keyword;
JSONParser jsonparser = new JSONParser();
ListView Datalist;
HorizontalScrollView VideoDatalist;
ArrayList<HashMap<String, String>> DataList;
ArrayList<HashMap<String, String>> VideoDataList;
JSONArray contacts = null;
private ProgressDialog pDialog;
ImageButton searchdata,InstallationView;
String Keyvalue = new String();
private static final String TAG_InnerText = "InnerText";
private static final String TAG_Title = "Title";
private static final String TAG_URL = "URL";
private static final String TAG_VIDEO_URL = "URL";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_data);
InstallationView=(ImageButton)findViewById(R.id.InstallationView);
Keyword = (EditText) findViewById(R.id.KeyData);
Datalist=(ListView)findViewById(R.layout.activity_installation);
VideoDatalist=(HorizontalScrollView)findViewById(R.id.Horizontallist);
searchdata=(ImageButton)findViewById(R.id.searchicon);
String Keyvalue = new String();
DataList = new ArrayList<HashMap<String, String>>();
VideoDataList = new ArrayList<HashMap<String, String>>();
searchdata.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new ReadData().execute();
}
});
InstallationView.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
startActivity(new Intent(SearchData.this, Installation.class));
}
});
}
public class ReadData extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchData.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
protected Void doInBackground(Void... arg0) {
try{
Keyvalue=Keyword.getText().toString();
String Jsonstr = jsonparser.makeHttpRequest("http://10.47.93.26:8080/Search/api/Search/"+Keyvalue);
try {
if (Jsonstr != null) {
JSONArray jsonObj = new JSONArray (Jsonstr);
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(i);
String name = c.optString(TAG_Title);
String url = c.optString(TAG_URL);
HashMap<String, String> info = new HashMap<String, String>();
if( !name.isEmpty() )
{
info.put(TAG_Title, name);
}
else
{
info.put(TAG_Title,"User Manual");
}
if(url.contains("youtube"))
{
info.put(TAG_URL, url);
VideoDataList.add(info);
}
else
{
info.put(TAG_URL, url);
DataList.add(info);
}
}
}
else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
SimpleAdapter adapter = new SimpleAdapter(
SearchData.this, DataList,
R.layout.list_item, new String[]
{
TAG_Title
}, new int[] {
R.id.InnerText });
Datalist.setAdapter(adapter);
}
}
}
web service running and parsing code is running correctly. i am getting error at post method,so can you help me on this.
Error
Call your Installation activity in onClick() method:
And pass your ArrayList data through intent,
InstallationView.setOnClickListener(new View.OnClickListener(){
public void onClick(View v)
{
Intent intent= new Intent(SearchData.this, Installation.class);
intent.putParcelableArrayListExtra("HASH_MAP",DataList);
startActivity(intent);
}
});
In your Installation activity class,set the view in onCreate() and initialize listview from xml file:
setContentView(R.layout.activity_installation);
ListView listView = (ListView)findViwById(R.id.listview);
And try to get the data from intent:
ArrayList<HashMap<String,String>> hashmap_dataList = getIntent.getParcelableArrayListExtra("HASH_MAP");
then do whatever you want with listview and hashmap.
In the onCreate(...) method of your SearchData Activity, the following can never work and will always return 'null' (hence your NullPointerException)...
Datalist=(ListView)findViewById(R.layout.activity_installation);
Calling findViewById(...) will only work for any UI elements which have been inflated when you called setContentView(...). In this case you used R.layout.activity_search_data for your layout file which doesn't contain a ListView with an id of R.layout.activity_installation which is, by the way, a resource id of a layout file and not a resource id of a UI element.
The only way you can do what you need is to put your data as an extra into the Intent you use when you call...
startActivity(new Intent(SearchData.this, Installation.class));
...when the Installation Activity is created it will then need to get the data and create its own adapter.
EDIT: HashMap is Serializable and can be passed as an Intent extra. Pass your DataList HashMap as follows...
Intent i = new Intent(SearchData.this, Installation.class);
i.putExtra("data_list", DataList);
startActivity(i);
In the Installation Activity you can then use...
getIntent().getSerializableExtra("data_list");

json search bar in android appthat searches a json file from an api server

i want to have a search bar that searches a number that has been typed in (for example: 115048) and put that in a listview. the json file looks like this http://api.ccapp.it/v1/student/115048/schedule/11
hope someone can help me, the code that i use right now to search a link is like this but it doesnt have a search bar:
public class RoosterviewMd extends ListActivity {
Button mButton;
EditText mEdit;
private ProgressDialog pDialog;
// URL to get contacts JSON
//private static String id = null;
//private static String url = "http://api.ccapp.it/v1/student/" + id + "/schedule/11";
private static String url = "http://api.ccapp.it/v1/student/115048/schedule/12";
// JSON Node names
private static final String TAG_LESSON = "class";
private static final String TAG_ROOM = "room";
private static final String TAG_TEACHER = "teacher";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.roosterviewmd);
//Number input
final EditText input = (EditText) findViewById(R.id.editText2);
//buttons for all the days
Button btn2 = (Button) findViewById(R.id.button29);
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Toast.makeText(getBaseContext(), "Je ziet je rooster voor maandag al" , Toast.LENGTH_SHORT ).show();
}
});
Button btnOne = (Button)findViewById(R.id.button30);
btnOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), RoosterviewDi.class);
startActivity(intent);
}
});
Button btnTwo = (Button)findViewById(R.id.button31);
btnTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), RoosterviewWo.class);
startActivity(intent);
}
});
Button btnThree = (Button)findViewById(R.id.button32);
btnThree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), RoosterviewDo.class);
startActivity(intent);
}
});
Button btnFour = (Button)findViewById(R.id.button33);
btnFour.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(), RoosterviewVr.class);
startActivity(intent);
}
});
//Buttons end here
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String lesson = ((TextView) view.findViewById(R.id.lesson))
.getText().toString();
String teacher = ((TextView) view.findViewById(R.id.teacher))
.getText().toString();
String room = ((TextView) view.findViewById(R.id.room))
.getText().toString();
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* 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(RoosterviewMd.this);
pDialog.setMessage("Give me a second please");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void 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);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray arr1 = jsonObj.getJSONArray("lessons");
JSONArray arr2 = arr1.getJSONArray(0); //Dag
for (int b = 0; b < arr2.length(); b++) {
JSONObject c = arr2.getJSONObject(b);
String lesson = c.getString(TAG_LESSON);
String teacher = c.getString(TAG_TEACHER);
String room = c.getString(TAG_ROOM);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_LESSON, lesson);
contact.put(TAG_TEACHER, teacher);
contact.put(TAG_ROOM, room);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("CCApp", "Couldn't get any data from the url");
Toast.makeText(getBaseContext(),"We are aware of this error and are working on it, in the mean time eat a cookie", Toast.LENGTH_LONG).show();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(RoosterviewMd.this, contactList,
R.layout.list_item, new String[] {TAG_LESSON, TAG_TEACHER,
TAG_ROOM }, new int[] { R.id.lesson,
R.id.teacher, R.id.room });
setListAdapter(adapter);
}
}
}
i hope someone can help me with this
Check out this answer: Get text from web page to string
Basically, you can simply get the text from the page and pass it into a string, and search the string application side for the contents of your edit text.
If you're looking for more functionality with the data from the web site, I would pull the Json into an array of Jsonobjects using something like Gson. You'd then be able to use the data from the web page in a bit more of a structured manner.
Edit: Now to actually answer your question.
You can include an edit text and button in your xml in order to search using a basic search bar kinda thing.
To set a listener on the button, you would do something like:
findViewById(R.id.button).setOnClickListener(new OnClickListener(){
#Override
protected void onClick(View v){
//Here, we can control what the response to the button press is, and grab the text in the edit text field.
String editTextString = findViewById(R.id.edittext).getEditableText().toString();
//Now we have a string used to parse the json or whatever else you need to do.
//May want to add a case here if editTextString is null to prevent runtime errors.
}
}
(Forgive me if there's any minor syntatic errors, just wrote that up quick here in the browser, no API to check on it. :))

Categories

Resources