Android - Multilevel Listviews - android

I am relatively new to Android and working with an online API. I have two activities. The first activity is bringing up a list of search results and placing them into a ListView. This is not a problem. I am trying to select an item from this ListView and pass it to the next activity and fill another ListView in this new activity with information from the selected item. This is where the problem is. The second activity never loads. What is a good way to get the second activity to work? I have been doing research and not getting the desired results. The code for the two activities and helper class are below.
Thank you
The first activity
import helper.ArtistCalendarHelper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import services.XMLParser;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class ArtistsSearchActivity extends ListActivity {
public static final String TAG = "ArtistsSearchActivity";
public static final String INTENT_EXTRAS_XML = "XML";
static final String KEY_ARTISTS = "artist";
static final String KEY_ID = "id";
static final String KEY_DISPLAY_NAME = "displayName";
static final String KEY_URI = "uri";
static final String KEY_ON_TOUR_UNTIL = "onTourUntil";
String onTourUntil ;
String displayName;
String identification;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_artists_search);
String xml = getIntent().getStringExtra(HomeActivity.INTENT_EXTRAS_XML);
List<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
addArtistsToHashmap(menuItems, xml);
addItemsToList(menuItems);
}
private void addItemsToList(List<HashMap<String, String>> menuItems) {
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item_artist_search, new String[] { KEY_ID, KEY_DISPLAY_NAME,
KEY_URI, KEY_ON_TOUR_UNTIL }, new int[] { R.id.tvId,
R.id.tvDisplayName, R.id.tvUri, R.id.tvOnTourUntil });
setListAdapter(adapter);
}
private void addArtistsToHashmap(List<HashMap<String, String>> menuItems,
String xml) {
XMLParser parser = new XMLParser();
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName(KEY_ARTISTS);
for (int i = 0; i < nl.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
map.put(KEY_ID, e.getAttribute(KEY_ID));
map.put(KEY_DISPLAY_NAME, e.getAttribute(KEY_DISPLAY_NAME));
map.put(KEY_URI, e.getAttribute(KEY_URI));
map.put(KEY_ON_TOUR_UNTIL, e.getAttribute(KEY_ON_TOUR_UNTIL));
menuItems.add(map);
}
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
displayName = ((TextView) view.findViewById(R.id.tvDisplayName)).getText().toString();
onTourUntil = ((TextView) view.findViewById(R.id.tvOnTourUntil)).getText().toString();
identification = ((TextView) view.findViewById(R.id.tvId)).getText().toString();
new AsyncDownload().execute(identification);
}
});
}
private class AsyncDownload extends AsyncTask<String, String, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ArtistsSearchActivity.this);
pDialog.setMessage("Please Wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
Log.v(TAG, "query is" + params[0]);
String result = new ArtistCalendarHelper().getXml(params[0]);
return result;
}
#Override
protected void onCancelled() {
super.onCancelled();
pDialog.dismiss();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
Log.v(TAG, "result=" + result);
Intent intent = new Intent();
intent.setClass(ArtistsSearchActivity.this, SingleArtistActivity.class);
intent.putExtra(KEY_DISPLAY_NAME, displayName);
intent.putExtra(KEY_ID, identification);
intent.putExtra(KEY_ON_TOUR_UNTIL, onTourUntil);
intent.putExtra(INTENT_EXTRAS_XML, result);
startActivity(intent);
}
}
}
The second activity
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import services.XMLParser;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class SingleArtistActivity extends ListActivity {
public static final String TAG = "SingleArtistActivity";
public static final String INTENT_EXTRAS_XML = "XML";
static final String KEY_VENUE = "event";
static final String KEY_VENUE_NAME = "displayName";
static final String KEY_DISPLAY_NAME = "displayName";
static final String KEY_ON_TOUR_UNTIL = "onTourUntil";
static final String KEY_ID = "id";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_artist);
// getting intent data
Intent in = getIntent();
// Get XML values from previous intent
String displayName = in.getStringExtra(KEY_DISPLAY_NAME);
String onTourUntil = in.getStringExtra(KEY_ON_TOUR_UNTIL);
String id = in.getStringExtra(KEY_ID);
// Displaying all values on the screen
TextView lblDisplayName = (TextView) findViewById(R.id.display_name_label);
TextView lblOnTourUntil = (TextView) findViewById(R.id.on_tour_until_label);
TextView lblID = (TextView) findViewById(R.id.id_label);
lblDisplayName.setText(displayName);
lblOnTourUntil.setText(onTourUntil);
lblID.setText(id);
String xml = getIntent().getStringExtra(HomeActivity.INTENT_EXTRAS_XML);
List<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
addItemsToList(menuItems);
addCalendarToHashmap(menuItems, xml);
}
private void addItemsToList(List<HashMap<String, String>> menuItems) {
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item_artist_calendar, new String[] { KEY_VENUE_NAME }, new int[] { R.id.calendarDisplayName });
setListAdapter(adapter);
}
private void addCalendarToHashmap(List<HashMap<String, String>> menuItems,
String xml) {
XMLParser parser = new XMLParser();
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName(KEY_VENUE);
for (int i = 0; i < nl.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
map.put(KEY_VENUE_NAME, e.getAttribute(KEY_VENUE_NAME));
menuItems.add(map);
}
}
}
And the my helper class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.util.Log;
public class LocationCalendarHelper {
private static final String TAG = "LocationCalendarHelper";
private static final String SONGKICK_URL = "http://api.songkick.com/api/3.0/metro_areas/";
private static final String API_KEY = "yIekMi1hQzcFheKc";
public String getXml(String searchQuery) {
HttpClient httpclient = new DefaultHttpClient();
String getParameters = "";
try {
getParameters = URLEncoder.encode(searchQuery, "UTF-8")
+ "/calendar.xml?apikey=" + URLEncoder.encode(API_KEY, "UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String url = SONGKICK_URL + getParameters;
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.i(TAG, response.getStatusLine().toString());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result = convertStreamToString(instream);
// now you have the string representation of the HTML request
instream.close();
return result;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return null;
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
My log cat errors. It starts with a bunch of xml so the activity is pulling in the information then ends with an error
05-10 07:09:41.587: V/ArtistsSearchActivity(796): <identifier mbid="eb558587-e7a1-4f2b-9fda-b6ff5e137ed1" href="http://api.songkick.com/api/3.0/artists/mbid:eb558587-e7a1-4f2b-9fda-b6ff5e137ed1.xml"/>
05-10 07:09:41.587: V/ArtistsSearchActivity(796): </artist>
05-10 07:09:41.587: V/ArtistsSearchActivity(796): </performance>
05-10 07:09:41.587: V/ArtistsSearchActivity(796): <performance billingIndex="3" displayName="Love And Death" billing="support" id="32720419">
05-10 07:09:41.587: V/ArtistsSearchActivity(796): <artist displayName="Love And Death" uri="http://www.songkick.com/artists/286472-love-and-death?utm_source=19089&utm_medium=partner" id="286472">
05-10 07:09:41.587: V/ArtistsSearchActivity(796): <identifier mbid="27796970-8f7a-4196-9f7d-87f091af4412" href="http://api.songkick.com/api/3.0/artists/mbid:27796970-8f7a-4196-9f7d-87f091af4412.xml"/>
05-10 07:09:41.587: V/ArtistsSearchActivity(796): <identifier mbid="c29b667e-9895-41d2-b5a5-1817050ce0bc" href="http://api.songkick.com/api/3.0/artists/mbid:c29b667e-9895-41d2-b5a5-1817050ce0bc.xml"/>
05-10 07:09:41.587: V/ArtistsSearchActivity(796): </artist>
05-10 07:09:41.587: V/ArtistsSearchActivity(796): </performance>
05-10 07:09:41.587: V/ArtistsSearchActivity(796): <venue displayName="Rostraver Ice Garden Arena" lat="40.1981235" lng="-79.8294916" uri="http://www.songkick.com/venues/51599-rostraver-ice-garden-arena?utm_source=19089&utm_medium=partner" id="51599">
05-10 07:09:41.587: V/ArtistsSearchActivity(796): <metroArea displayName="Belle Vernon" uri="http://www.songkick.com/metro_areas/56020-us-belle-vernon?utm_source=19089&utm_medium=partner" id="56020">
05-10 07:09:41.587: V/ArtistsSearchActivity(796): <state displayName="PA"/>
05-10 07:09:41.587: V/ArtistsSearchActivity(796): <country displayName="US"/>
05-10 07:09:41.587: V/ArtistsSearchActivity(796): </metroArea>
05-10 07:09:41.587: V/ArtistsSearchActivity(796): </venue>
05-10 07:09:41.587: V/ArtistsSearchActivity(796): <start time="19:30:00" datetime="2013-05-15T19:30:00-0500" date="2013-05-15"/>
05-10 07:09:41.587: V/ArtistsSearchActivity(796): <location lat="40.1981235" lng="-79.8294916" city="Belle Vernon, PA, US"/>
05-10 07:09:41.587: V/ArtistsSearchActivity(796): </event>
05-10 07:09:41.587: V/ArtistsSearchActivity(796): <event type="Festival" status="ok" displayName="Rock on the Range 2013" uri="http://www.songkick.com/festivals/8261/id/14745014-rock-on-the-range-2013?utm_source=19089&utm_medium=partner" popularity="0
05-10 07:09:41.637: I/Choreographer(796): Skipped 49 frames! The application may be doing too much work on its main thread.
05-10 07:09:43.807: E/Trace(871): error opening trace file: No such file or directory (2)
05-10 07:09:45.357: E/Trace(910): error opening trace file: No such file or directory (2)
05-10 07:09:45.687: E/Trace(923): error opening trace file: No such file or directory (2)
05-10 07:09:46.307: E/Trace(936): error opening trace file: No such file or directory (2)
05-10 07:09:47.167: E/Trace(949): error opening trace file: No such file or directory (2)
05-10 07:09:48.337: E/Trace(975): error opening trace file: No such file or directory (2)
I have an update. The above code works! I will leave it for those that need it. The problem I am having is that if the xml string is too long the search times out. So how do I give Android more time to do its search?

private void addItemsToList(List<HashMap<String, String>> menuItems) {
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item_artist_calendar, new String[] { KEY_VENUE_NAME }, new int[] { R.id.calendarDisplayName });
setListAdapter(adapter);
adapter.notifyDataSetChanged();
}

Related

Android Studio ListViewAdapter Error

please help me with this problem..
i change my previous question to this..
i cant post new question because im in danger of being blocked..
heres my problem..
im trying to get data from database but i got this error when i run the app..
09-29 13:41:07.032 26507-26507/? E/Error﹕ No value for result
09-29 13:41:07.032 26507-26507/? W/System.err﹕ org.json.JSONException: No value for result
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at org.json.JSONObject.get(JSONObject.java:354)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at org.json.JSONObject.getJSONArray(JSONObject.java:548)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at com.example.administrator.mosbeau.CategoryFragment.prepareListData(CategoryFragment.java:249)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at com.example.administrator.mosbeau.CategoryFragment$1GetDataJSON.onPostExecute(CategoryFragment.java:233)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at com.example.administrator.mosbeau.CategoryFragment$1GetDataJSON.onPostExecute(CategoryFragment.java:180)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at android.os.AsyncTask.finish(AsyncTask.java:631)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at android.os.AsyncTask.access$600(AsyncTask.java:177)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:99)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at android.os.Looper.loop(Looper.java:137)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5494)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:525)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:875)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:691)
09-29 13:41:07.032 26507-26507/? W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
09-29 13:41:07.042 26507-26507/? I/MemoryCache﹕ MemoryCache will use up to 24.0MB
09-29 13:41:07.042 26507-26507/? D/AndroidRuntime﹕ Shutting down VM
09-29 13:41:07.042 26507-26507/? W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x418e38e0)
09-29 13:41:07.042 26507-26507/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.administrator.mosbeau.ListViewAdapter.getCount(ListViewAdapter.java:38)
at android.widget.ListView.setAdapter(ListView.java:463)
at com.example.administrator.mosbeau.CategoryFragment$1GetDataJSON.onPostExecute(CategoryFragment.java:236)
at com.example.administrator.mosbeau.CategoryFragment$1GetDataJSON.onPostExecute(CategoryFragment.java:180)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5494)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:875)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:691)
at dalvik.system.NativeStart.main(Native Method)
09-29 13:41:07.052 941-7799/? I/ActivityManager﹕ Notify an ApplicationCrash
here is the code..
CategoryFragment.java
package com.example.administrator.mosbeau;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ListView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by Administrator on 9/18/2015.
*/
public class CategoryFragment extends Fragment {
public static CategoryFragment newInstance(String id,String name) {
CategoryFragment fragment = new CategoryFragment();
Bundle bundle = new Bundle();
bundle.putString("id", id);
bundle.putString("name", name);
fragment.setArguments(bundle);
return fragment;
}
public CategoryFragment () {
}
EditText tpid, tpname;
String cid;
String cname;
String myJSON;
JSONObject jsonobject;
JSONArray jsonarray;
ListView productlistview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static final String result="result";
static String products_id = "products_id";
static String products_name = "products_name";
static String products_price = "products_price";
static String products_image = "products_image";
Boolean InternetAvailable = false;
Seocnd detectconnection;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.categorylayout, container, false);
getActivity().invalidateOptionsMenu();
tpid = (EditText) rootView.findViewById(R.id.tpid);
tpname = (EditText) rootView.findViewById(R.id.tpname);
if(getArguments() != null) {
String catid = getArguments().getString("id");
String catname = getArguments().getString("name");
tpid.setText(catid);
tpname.setText(catname);
cid = catid;
cname = catname;
}
productlistview = (ListView) rootView.findViewById(R.id.productlistview);
//new DownloadJSON().execute();
detectconnection = new Seocnd(getActivity());
InternetAvailable = detectconnection.InternetConnecting();
if (InternetAvailable) {
getProduct();
} else {
NointernetFragment fragment = new NointernetFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
return rootView;
}
public void getProduct(){
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle(cname);
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://joehamirbalabadan.com/android/android/products.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
prepareListData();
adapter = new ListViewAdapter(getActivity(), arraylist);
// Set the adapter to the ListView
productlistview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
protected void prepareListData(){
try {
// Locate the array name in JSON
JSONObject jsonObj = new JSONObject(myJSON);
jsonarray = jsonObj.getJSONArray(result);
HashMap<String, String> map = new HashMap<String, String>();
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject p = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("products_id", p.getString("products_id"));
map.put("products_name", p.getString("products_name"));
map.put("products_price", p.getString("products_price"));
map.put("products_image", p.getString("products_image"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(2);
}
}
ListViewAdapter.java
package com.example.administrator.mosbeau;
/**
* Created by Administrator on 9/28/2015.
*/
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView products_id;
TextView products_name;
TextView products_price;
ImageView products_image;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.product_listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in product_listview_item.xml
products_id = (TextView) itemView.findViewById(R.id.products_id);
products_name = (TextView) itemView.findViewById(R.id.products_name);
products_price = (TextView) itemView.findViewById(R.id.products_price);
// Locate the ImageView in product_listview_item.xml
products_image = (ImageView) itemView.findViewById(R.id.products_image);
// Capture position and set results to the TextViews
products_id.setText(resultp.get(CategoryFragment.products_id));
products_name.setText(resultp.get(CategoryFragment.products_name));
products_price.setText(resultp.get(CategoryFragment.products_price));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(CategoryFragment.products_image), products_image);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, SingleItemView.class);
// Pass all data rank
intent.putExtra("products_id", resultp.get(CategoryFragment.products_id));
// Pass all data country
intent.putExtra("products_name", resultp.get(CategoryFragment.products_name));
// Pass all data population
intent.putExtra("products_price",resultp.get(CategoryFragment.products_price));
// Pass all data flag
intent.putExtra("products_image", resultp.get(CategoryFragment.products_image));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return itemView;
}
}
NEW ERROR
09-29 14:12:26.981 593-593/? W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x409bf1f8)
09-29 14:12:26.992 593-593/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.administrator.mosbeau.CategoryFragment.prepareListData(CategoryFragment.java:259)
at com.example.administrator.mosbeau.CategoryFragment$1GetDataJSON.onPostExecute(CategoryFragment.java:232)
at com.example.administrator.mosbeau.CategoryFragment$1GetDataJSON.onPostExecute(CategoryFragment.java:179)
at android.os.AsyncTask.finish(AsyncTask.java:602)
at android.os.AsyncTask.access$600(AsyncTask.java:156)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:615)
this is line 259
arraylist.add(map);
line 232
prepareListData();
UPDATED CODE
CategoryFragment.java
package com.example.administrator.mosbeau;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ListView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by Administrator on 9/18/2015.
*/
public class CategoryFragment extends Fragment {
public static CategoryFragment newInstance(String id,String name) {
CategoryFragment fragment = new CategoryFragment();
Bundle bundle = new Bundle();
bundle.putString("id", id);
bundle.putString("name", name);
fragment.setArguments(bundle);
return fragment;
}
public CategoryFragment () {
}
EditText tpid, tpname;
String cid;
String cname;
String myJSON;
JSONObject jsonobject;
JSONArray jsonarray;
ListView productlistview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
public static String products_id = "products_id";
public static String products_name = "products_name";
public static String products_price = "products_price";
public static String products_image = "products_image";
Boolean InternetAvailable = false;
Seocnd detectconnection;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.categorylayout, container, false);
getActivity().invalidateOptionsMenu();
tpid = (EditText) rootView.findViewById(R.id.tpid);
tpname = (EditText) rootView.findViewById(R.id.tpname);
if(getArguments() != null) {
String catid = getArguments().getString("id");
String catname = getArguments().getString("name");
tpid.setText(catid);
tpname.setText(catname);
cid = catid;
cname = catname;
}
productlistview = (ListView) rootView.findViewById(R.id.productlistview);
//new DownloadJSON().execute();
detectconnection = new Seocnd(getActivity());
InternetAvailable = detectconnection.InternetConnecting();
if (InternetAvailable) {
getProduct();
} else {
NointernetFragment fragment = new NointernetFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
return rootView;
}
public void getProduct(){
class DownloadJSON extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle(cname);
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://joehamirbalabadan.com/android/android/products.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
try {
// Locate the array name in JSON
JSONObject jsonObj = new JSONObject(myJSON);
jsonarray = jsonObj.getJSONArray("products");
arraylist = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject p = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("products_id", p.getString("products_id"));
map.put("products_name", p.getString("products_name"));
map.put("products_price", p.getString("products_price"));
map.put("products_image", p.getString("products_image"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
adapter = new ListViewAdapter(getActivity(), arraylist);
// Set the adapter to the ListView
productlistview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
DownloadJSON g = new DownloadJSON();
g.execute();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(2);
}
}
the image is not displaying when i use the .php file in this code..
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://joehamirbalabadan.com/android/android/products.php");
but when i use the .txt file it works..
i tried to copy the data of products.php and save it as .txt then when i change the link to this http://joehamirbalabadan.com/android/android/products.txt..
it works.. but i want to use the .php file because i use this to get the data from database..
products.php result
products.txt result
please help me..
Try to initialize arraylist first and also create HashMap item new instance inside for loop like :
protected void prepareListData(){
try {
arraylist = new ArrayList<HashMap<String, String>>();
// Locate the array name in JSON
JSONObject jsonObj = new JSONObject(myJSON);
jsonarray = jsonObj.getJSONArray(result);
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject p = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("products_id", p.getString("products_id"));
map.put("products_name", p.getString("products_name"));
map.put("products_price", p.getString("products_price"));
map.put("products_image", p.getString("products_image"));
// Set the JSON Objects into the array
arraylist.add(map);
}
catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
}
Initialize your result string with products like this one:
static final String result="products";
It will work
I think you need to decalre below variables
static final String result="result";
static String products_id = "products_id";
static String products_name = "products_name";
static String products_price = "products_price";
static String products_image = "products_image";
which you have to change like this
public static final String result="result";
public static String products_id = "products_id";
public static String products_name = "products_name";
public static String products_price = "products_price";
public static String products_image = "products_image";
I hope it work.

Search in listview and show the result

how is it possible to parse some Json Data from web and put them in a listview.
Inside of them i would like to search something, I'm searching now for a while in the internet but I wasn't successfull.
I still can Parse JSON and pu them in a listview but how can I search?
Here my Code
MainAct.:
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
ListView list;
TextView ver;
TextView name;
TextView api;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "*****";
//JSON Node Names
private static final String TAG_OS = "android";
private static final String TAG_VER = "ver";
private static final String TAG_NAME = "name";
private static final String TAG_API = "api";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.vers);
name = (TextView)findViewById(R.id.name);
api = (TextView)findViewById(R.id.api);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#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
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
JSONParser:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
List<list> varr = yourlist;
for (list result : varr) {
// action such as.. if result
}
hope this help

list view parsing data to another activity using intent

I have a listview now i need to pass the listview data to a another activity how do i do it ?
MainActivity
package learn2crack.listview;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import java.util.List;
import android.view.Menu;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import learn2crack.listview.library.JSONParser;
public class MainActivity extends Activity {
ListView list;
TextView ver;
TextView name;
TextView api;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
private static String url = "http://216.185.116.35/LOGISTIC/WebServices/json/getDeliveriItems_bak.ashx?id=485";
private static final String TAG_OS = "android";
private static final String TAG_VER = "BagNumber";
private static final String TAG_NAME = "COD";
private static final String TAG_API = "OrderNo";
JSONArray android = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
ver = (TextView)findViewById(R.id.vers);
name = (TextView)findViewById(R.id.name);
api = (TextView)findViewById(R.id.api);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
listAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,R.layout.list_v,new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
JSONParser.java
package learn2crack.listview.library;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
json = sb.toString();
json = "{ \"android\":"+json+"}";
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
}
I have found some explanation how to pass data but I am having problem at new AdapterView.OnItemClickListener()
The problem is
oslist.get(+position)
should be
oslist.get(position)
Also you have
private static final String TAG_NAME = "COD"; // key for name is COD
map.put(TAG_NAME, name);
then
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String name = oslist.get(position).get("COD");
Intent intent = new Intent(ActivityName.this, YOURACTIVITY.class);
intent.putExtra("key", name);
startActivity(intent);
}
});
Should move setAdapter coe out of for loop
Also change to
#Override
protected void onPostExecute(JSONObject json) {
super.onPostExecute(json);
pDialog.dismiss();
try {
android = json.getJSONArray(TAG_OS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
String ver = c.getString(TAG_VER);
String name = c.getString(TAG_NAME);
String api = c.getString(TAG_API);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_VER, ver);
map.put(TAG_NAME, name);
map.put(TAG_API, api);
oslist.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
list=(ListView)findViewById(R.id.list);
listAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,R.layout.list_v,new String[] { TAG_VER,TAG_NAME, TAG_API }, new int[] {
R.id.vers,R.id.name, R.id.api});
list.setAdapter(adapter)
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String name = oslist.get(position).get("COD");
String ver = oslist.get(position).get(TAG_VER);
String api = oslist.get(position).get(TAG_API);
Intent intent = new Intent(MainActivity.this, AnotherActivity.class);
intent.putExtra("key", name);
intent.putExtra("key1", ver);
intent.putExtra("key2", api);
startActivity(intent);
}
});
}
In Another Activtiy
String name =getIntent().getStringExtra("key");
String api =getIntent().getStringExtra("key1");
String ver =getIntent().getStringExtra("key"2);
You should create a custom adapter. Also create a DataModel which will hold all the 3 values (Version, Name and Api). Make it Serializable.
public class MyModel implements Serializable{
private static final long serialVersionUID = 1L;
String version, name, api;
public MyModel(String modelVer, String modelName, String modelApi){
version = modelVer;
name = modelName ;
api = modelApi;
}
//Add Getters and Setters
}
Instead of creating HashMap<String, String> map = new HashMap<String, String>(); Create
ArrayList<MyModel> modelList = new ArrayList<MyModel>();
then in OnItemClickListener()
//To send data
MyModel modelToPass = modelList.get(position);
intent.putExtra("MyObject", modelToPass);
//To get data
getIntent().getSerializableExtra("MyObject");
for example you can pass the position of item that is clicked by below code
public void onListItemClick(ListView parent, View v, int position,
long id){
Intent intent = new Intent(getApplicationContext(), YourActivity.class);
intent.putExtra("pos", position);
startActivity(intent);
}
in YourActivity oncreate() method
Intent current=getIntent();
int position=current.getExtras().getInt("pos");
for sending your data you can make class below
public class Information implements Serializable {
public String BagNumber;
public String COD;
public String OrderNo;
public String SubOrderNo;
......
......
}
and for send it
Information details = new Information ();
details.BagNumber = "";
details.COD = "12";
details.OrderNo = "ff";
....
....
Intent i = new Intent(getApplicationContext(), YourActivity.class);
i.putExtra("inf", details);
startActivity(i);
For receive it
Information model = (Information ) getIntent().getSerializableExtra("inf");

How to get the distance and duration from Google Directions API

I'm developing an Android app in which I created an activity that shows a list of directions taken from Google Directions API.
The url used is something like this: http://maps.googleapis.com/maps/api/directions/xml?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false
And the result is something like this:
<DirectionsResponse>
<status>OK</status>
<route>
<summary>I-40 W</summary>
<leg>
<step>
<travel_mode>DRIVING</travel_mode>
<start_location>
<lat>41.8507300</lat>
<lng>-87.6512600</lng>
</start_location>
<end_location>
<lat>41.8525800</lat>
<lng>-87.6514100</lng>
</end_location>
<polyline>
<points>a~l~Fjk~uOwHJy#P</points>
</polyline>
<duration>
<value>19</value>
<text>1 min</text>
</duration>
<html_instructions>Head <b>north</b> on <b>S Morgan St</b> toward <b>W Cermak Rd</b></html_instructions>
<distance>
<value>207</value>
<text>0.1 mi</text>
</distance>
</step>
...
... additional steps of this leg
...
... additional legs of this route
<duration>
<value>74384</value>
<text>20 hours 40 mins</text>
</duration>
<distance>
<value>2137146</value>
<text>1,328 mi</text>
</distance>
<start_location>
<lat>35.4675602</lat>
<lng>-97.5164276</lng>
</start_location>
<end_location>
<lat>34.0522342</lat>
<lng>-118.2436849</lng>
</end_location>
<start_address>Oklahoma City, OK, USA</start_address>
<end_address>Los Angeles, CA, USA</end_address>
<copyrights>Map data ©2010 Google, Sanborn</copyrights>
<overview_polyline>
<points>a~l~Fjk~uOnzh#vlbBtc~#tsE`vnApw{A`dw#~w\|tNtqf#l{Yd_Fblh#rxo#b}#xxSfytAblk#xxaBeJxlcBb~t#zbh#jc|Bx}C`rv#rw|#rlhA~dVzeo#vrSnc}Axf]fjz#xfFbw~#dz{A~d{A|zOxbrBbdUvpo#`cFp~xBc`Hk#nurDznmFfwMbwz#bbl#lq~#loPpxq#bw_#v|{CbtY~jGqeMb{iF|n\~mbDzeVh_Wr|Efc\x`Ij{kE}mAb~uF{cNd}xBjp]fulBiwJpgg#|kHntyArpb#bijCk_Kv~eGyqTj_|#`uV`k|DcsNdwxAott#r}q#_gc#nu`CnvHx`k#dse#j|p#zpiAp|gEicy#`omFvaErfo#igQxnlApqGze~AsyRzrjAb__#ftyB}pIlo_BflmA~yQftNboWzoAlzp#mz`#|}_#fda#jakEitAn{fB_a]lexClshBtmqAdmY_hLxiZd~XtaBndgC</points>
</overview_polyline>
<optimized_waypoint_index>0</optimized_waypoint_index>
<optimized_waypoint_index>1</optimized_waypoint_index>
<bounds>
<southwest>
<lat>34.0523600</lat>
<lng>-118.2435600</lng>
</southwest>
<northeast>
<lat>41.8781100</lat>
<lng>-87.6297900</lng>
</northeast>
</bounds>
</route>
</DirectionsResponse>
In every item of the list I want to show the information contained in <html_instructions>, <text> child of <distance> and <text> child of <duration>.
I was able to obtain the value of <html_instructions> tag, using this parser:
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.util.Log;
public class XMLParser {
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
// return DOM
return doc;
}
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
public final String getElementValue(Node elem) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
}
How can I modify this parser in order to shows also the values of the other two tags?
I was able to fix that by adding another method in XMLParser class:
public String getSecondValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(1));
}
and here is the usage in the activity:
import java.util.ArrayList;
import java.util.HashMap;
import maps.XMLParser;
import org.apache.commons.lang3.StringEscapeUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class DirectionsActivity extends ListActivity {
String url = "";
XMLParser parser;
String xml = "";
ArrayList<HashMap<String, String>> menuItems;
// All static variables
static final String KEY_STEP = "step"; // parent node
static final String KEY_HTML_INSTRUCTIONS = "html_instructions";
static final String KEY_DURATION = "duration";
static final String KEY_DISTANCE = "distance";
static final String KEY_TEXT = "text";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = this.getIntent();
url = intent.getExtras().getString("url");
System.out.println("---------------" + url);
menuItems = new ArrayList<HashMap<String, String>>();
parser = new XMLParser();
DownloadTask downloadTask = new DownloadTask();
// Start downloading XML data from Google Directions API
downloadTask.execute(url);
// selecting single ListView item
ListView lv = getListView();
// listening to single listitem click
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String instruction = ((TextView) view.findViewById(R.id.instruction)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_HTML_INSTRUCTIONS, instruction);
startActivity(in);
}
});
}
/** A class to download data from Google Directions URL */
private class DownloadTask extends AsyncTask<String, Void, String>{
ListAdapter adapter;
private ProgressDialog pd;
#Override
protected void onPreExecute() {
pd = new ProgressDialog(DirectionsActivity.this);
pd.setTitle("Processing...");
pd.setMessage("Calcolo direzione in corso dalla posizione corrente...");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
// Downloading data in non-ui thread
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try{
// Fetching the data from web service
data = parser.getXmlFromUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executes in UI thread, after the execution of
// doInBackground()
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Document doc = parser.getDomElement(result); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_STEP);
// looping through all item nodes <step>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
String escapedKeyHtmlInstructions = StringEscapeUtils.escapeHtml4(KEY_HTML_INSTRUCTIONS);
// KEY_HTML_INSTRUCTIONS.replaceAll("\\<.*?>", "");
map.put(KEY_HTML_INSTRUCTIONS, parser.getValue(e, escapedKeyHtmlInstructions));
map.put(KEY_DURATION, parser.getValue(e, KEY_TEXT));
map.put(KEY_DISTANCE, parser.getSecondValue(e, KEY_TEXT));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
adapter = new SimpleAdapter(DirectionsActivity.this, menuItems,R.layout.list_item,
new String[] { KEY_HTML_INSTRUCTIONS, KEY_DURATION, KEY_DISTANCE}, new int[] {
R.id.instruction, R.id.duration, R.id.distance});
setListAdapter(adapter);
pd.dismiss();
}
}
}

Android-Json parser not able to display data retrieved from back end

I am new to android. I am implementing a project in which I want to get the data from the back end and display on my android screen.
The Json I am trying to call is:-
[{"admin":null,"card_no":"8789","created_at":"2013-04-09T12:55:54Z","deleted":0,"email":"dfds#fgfd.com","entered_by":null,"first_name":"Gajanan","id":8,"last_name":"Bhat","last_updated_by":null,"middle_name":"","mobile":87981,"updated_at":"2013-04-13T05:26:25Z","user_type_id":null},{"admin":{"created_at":"2013-04-10T09:02:00Z","deleted":0,"designation":"Sr software Engineer","email":"admin#qwe.com","first_name":"Chiron","id":1,"last_name":"Synergies","middle_name":"Sr software Engineer","office_phone":"98789765","super_admin":false,"updated_at":"2013-04-10T12:03:04Z","username":"Admin"},"card_no":"66","created_at":"2013-04-08T09:47:15Z","deleted":0,"email":"rajaarun1991","entered_by":1,"first_name":"Arun","id":1,"last_name":"Raja\n","last_updated_by":1,"middle_name":"Nagaraj","mobile":941,"updated_at":"2013-04-08T09:47:15Z","user_type_id":1}]
My JsonParser.java is as follows:-
package com.example.library;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONArray jarray = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONArray getJSONFromUrl(String url) {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
} else {
Log.e("==>", "Failed to download file");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jarray = new JSONArray( builder.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jarray;
}
}
/* public void writeJSON() {
JSONObject object = new JSONObject();
try {
object.put("name", "");
object.put("score", new Integer(200));
object.put("current", new Double(152.32));
object.put("nickname", "Programmer");
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(object);
}
*/
And my activity.java is as follows:-
package com.example.library;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class SecondActivity extends Activity
{
private Context context;
private static String url = "http://192.168.0.100:3000/users.json";
private static final String TAG_ID = "id";
private static final String TAG_FIRST_NAME = "first_name";
private static final String TAG_MIDDLE_NAME = "middle_name";
private static final String TAG_LAST_NAME = "last_name";
// private static final String TAG_POINTS = "experiencePoints";
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
ListView lv ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new ProgressTask(SecondActivity.this).execute();
}
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog;
public ProgressTask(SecondActivity secondActivity) {
Log.i("1", "Called");
context = secondActivity;
dialog = new ProgressDialog(context);
}
/** progress dialog to show user that the backup is processing. */
/** application context. */
private Context context;
protected void onPreExecute() {
this.dialog.setMessage("Progress start");
this.dialog.show();
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(context, jsonlist,
R.layout.list_item, new String[] { TAG_ID, TAG_FIRST_NAME,
TAG_MIDDLE_NAME, TAG_LAST_NAME }, new int[] {
R.id.id, R.id.first_name, R.id.middle_name,
R.id.last_name });
setListAdapter(adapter);
// selecting single ListView item
lv = getListView();
}
private void setListAdapter(ListAdapter adapter) {
// TODO Auto-generated method stub
}
protected Boolean doInBackground(final String... args) {
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
String id = c.getString(TAG_ID);
String first_name = c.getString(TAG_FIRST_NAME);
String middle_name = c.getString(TAG_MIDDLE_NAME);
String last_name = c.getString(TAG_LAST_NAME);
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_FIRST_NAME, first_name);
map.put(TAG_MIDDLE_NAME, middle_name);
map.put(TAG_LAST_NAME, last_name);
jsonlist.add(map);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
}
public ListView getListView() {
// TODO Auto-generated method stub
return null;
}
}
I am not able to show anything on the emulators for users,whereas I am able to fetch the data from the server
Actually in the project I want to display all the users present in the library.I am accessing the server which is on Ubuntu.
The following message is displayed on the console(Terminal):-
Started GET "/users.json" for 192.168.0.104 at 2013-05-05 22:05:01 -0700
Processing by UsersController#index as JSON
User Load (0.4ms) SELECT "users".* FROM "users" WHERE (users.deleted = 0) ORDER BY users.id DESC
Admin Load (0.3ms) SELECT "admins".* FROM "admins" WHERE "admins"."id" = 1 AND (admins.deleted = 0) ORDER BY admins.id DESC LIMIT 1
Completed 200 OK in 4ms (Views: 2.1ms | ActiveRecord: 0.6ms)
[2013-05-05 22:05:01] WARN Could not determine content-length of response body. Set content-length of the response or set Response#chunked = true
However i am not able to display the data on the android screen/emulator.
Please help me with this.
I missed your setAdapterList()method.
Any error for your json pasers? and can you put your activity which is inherited from SecondActivity?
//modify getListView
public ListView getListView() {
// TODO Auto-generated method stub
listView = (ListView)findViewById(r.your.listview);
return listView;
}
//modify setListAdapter
private void setListAdapter(ListAdapter adapter) {
// TODO Auto-generated method stub
lv.setAdapter(adapter);
}

Categories

Resources