I am trying to fit a Google Maps View and a ListView into one activity. The MapsView shall take 2/3 of the upper side, and the list 1/3 of the lower side (in portrait).
in this way assume it as portrait:
Both, the MapsView and the ListView, will receive the same JSON information, they will get onCreate(). I was already able to fit the MapsView on 2/3 of the screen, but the ListView wont receive any data. Can someone tell me, how to adress a ListView correct, when the superclass isnt ListActivity?
here is my code:
// url to make request
private static String url = ""; //here pass the url
// JSON Node names
private static final String TAG_LOCATION = "location";
private static final String TAG_LOCATION1= "location";
private static final String TAG_LOCATION_ID = "LocationID";
private static final String TAG_NAME = "Name";
private static final String TAG_PHONE = "Phone";
private static final String TAG_FORMATTED_PHONE = "FormattedPhone";
private static final String TAG_ADDRESS = "Address";
private static final String TAG_CROSS_STREET = "CrossStreet";
private static final String TAG_LAT = "Lat";
private static final String TAG_LNG = "Lng";
private static final String TAG_DISTANCE= "Distance";
private static final String TAG_POSTAL_CODE = "PostalCode";
private static final String TAG_CITY = "City";
private static final String TAG_STATE = "State";
private static final String TAG_COUNTRY= "Country";
// contacts JSONArray
JSONArray location = null;
JSONObject location1=null;
ListView locationList;
private MapView mapView;
LocationManager lm;
LocationListener locationListener;
MapController mapController;
private ListAdapter adapter;
private static final double lat = 11.9333;
private static final double lng = 108.417;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_map);
locationList=( ListView)findViewById(R.id.list_Surroundings);
locationList.setAdapter(adapter);
// Hashmap for ListView
ArrayList<HashMap<String, String>> locationList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Category
location=json.getJSONArray(TAG_LOCATION);
//looping through all categories
for(int i = 0; i < location.length(); i++){
JSONObject c = location.getJSONObject(i);
JSONObject c1=c.getJSONObject(TAG_LOCATION1);
// Storing each json item in variable
String LocationID = c1.getString(TAG_LOCATION_ID);
String Name = c1.getString(TAG_NAME);
String Phone = c1.getString(TAG_PHONE);
String FormattedPhone = c1.getString(TAG_FORMATTED_PHONE);
String Address = c1.getString(TAG_ADDRESS);
String CrossStreet = c1.getString(TAG_CROSS_STREET);
String Lat = c1.getString(TAG_LAT);
String Lng = c1.getString(TAG_LNG);
String Distance = c1.getString(TAG_DISTANCE);
String PostalCode = c1.getString(TAG_POSTAL_CODE);
String City = c1.getString(TAG_CITY);
String State = c1.getString(TAG_STATE);
String Country = c1.getString(TAG_COUNTRY);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_LOCATION_ID, LocationID);
map.put(TAG_NAME, Name);
map.put(TAG_PHONE, Phone);
map.put(TAG_FORMATTED_PHONE, FormattedPhone);
map.put(TAG_ADDRESS, Address);
map.put(TAG_CROSS_STREET, CrossStreet);
map.put(TAG_LAT, Lat);
map.put(TAG_LNG, Lng);
map.put(TAG_DISTANCE, Distance);
map.put(TAG_POSTAL_CODE, PostalCode);
map.put(TAG_CITY, City);
map.put(TAG_STATE, State);
map.put(TAG_COUNTRY, Country);
// adding HashList to ArrayList
locationList.add(map);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
adapter = new SimpleAdapter(this, locationList,
R.layout.list_item,
new String[] { TAG_NAME }, new int[] {
R.id.name});
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
List mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(
R.drawable.map_pin_red);
CustomItemizedOverlay itemizedOverlay = new CustomItemizedOverlay(
drawable, this);
GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
OverlayItem overlayitem = new OverlayItem(point, "Hello",
"I'm in Athens, Greece!");
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
mapController = mapView.getController();
mapController.animateTo(point);
mapController.setZoom(10);
lm=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationListener= new MylocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
public class MylocationListener implements LocationListener{
#Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
if(loc!=null){
Toast.makeText(getBaseContext(), "Location Changed : Lat:" +loc.getLatitude() + "Lng: " + loc.getLongitude(), Toast.LENGTH_SHORT).show();
}
GeoPoint point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
mapController.animateTo(point);
mapController.setZoom(10);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
You have to create the adapter BEFORE setting it as the adapter of the ListView. Also, you have two variables named LocationList, which is generally bad practice. Try:
public void onCreate(Bundle savedInstanceState) {
// Hashmap for ListView
ArrayList<HashMap<String, String>> listOfLocations = new ArrayList<HashMap<String, String>>();
... // existing code here
adapter = new SimpleAdapter(this, listOfLocations,
R.layout.list_item,
new String[] { TAG_NAME }, new int[] {
R.id.name});
locationList.setAdapter(adapter);
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am trying to select the first index in listview on first load onCreate. I've try the listView.setSelection(0) but some error occur. this is my code...
public class QandAPractice extends AppCompatActivity {
String qsid;
ListView listView;
ArrayList<String> myqid;
RadioButton r1,r2,r3,r4;
String txtcontent, txtTimer,txtAnskey,txtImg, txtA, txtB, txtC, txtD, txtID;
private static final String TAG_QID = "id";
private static final String TAG_TITLE = "content";
private static final String TAG_TIMER = "timer";
private static final String TAG_IMAGE = "images";
private static final String TAG_QSID = "qsid";
private static final String TAG_KEY = "key";
private static final String TAG_A = "A";
private static final String TAG_B = "B";
private static final String TAG_C = "C";
private static final String TAG_D = "D";
ArrayList<HashMap<String, String>> questions;
Dialog quizDialog;
public int i = 60;
public int loadindex = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qand_apractice);
questions = new ArrayList<>();
myqid = new ArrayList<>();
Bundle b = getIntent().getExtras();
setTitle(b.getString("subject"));
qsid = b.getString("qsid");
quizDialog = new Dialog(this,android.R.style.Theme_Black_NoTitleBar_Fullscreen);
listView = findViewById(R.id.lvquestions);
getJSON(Constants.ROOT_URL+"mobile_question_index.php?qsid="+qsid);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
txtID = ((TextView) view.findViewById(R.id.quiz_id)).getText()
.toString();
txtcontent = ((TextView) view.findViewById(R.id.quiz_content)).getText()
.toString();
txtTimer = ((TextView) view.findViewById(R.id.quiz_timer)).getText()
.toString();
txtAnskey = ((TextView) view.findViewById(R.id.quiz_key)).getText()
.toString();
txtA = ((TextView) view.findViewById(R.id.quiz_A)).getText()
.toString();
txtB = ((TextView) view.findViewById(R.id.quiz_B)).getText()
.toString();
txtC = ((TextView) view.findViewById(R.id.quiz_C)).getText()
.toString();
txtD = ((TextView) view.findViewById(R.id.quiz_D)).getText()
.toString();
txtImg = ((TextView) view.findViewById(R.id.quiz_image)).getText()
.toString();
showQuiz();
}
});
listView.setSelection(0);
listView.getSelectedView().setSelected(true);
}
private void getJSON(final String urlWebService) {
class GetJSON extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
loadIntoListView(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON();
getJSON.execute();
}
private void loadIntoListView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
//String[] question = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String id = obj.getString(TAG_QID);
String content = obj.getString(TAG_TITLE);
String image = obj.getString(TAG_IMAGE);
String a = obj.getString(TAG_A);
String b = obj.getString(TAG_B);
String c = obj.getString(TAG_C);
String d = obj.getString(TAG_D);
String key = obj.getString(TAG_KEY);
String timer = obj.getString(TAG_TIMER);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_QID,id);
map.put(TAG_TITLE,content);
map.put(TAG_IMAGE,image);
map.put(TAG_A,a);
map.put(TAG_B,b);
map.put(TAG_C,c);
map.put(TAG_D,d);
map.put(TAG_KEY,key);
map.put(TAG_TIMER,timer);
myqid.add(id);
questions.add(map);
}
// ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, question);
SimpleAdapter adapter = new SimpleAdapter(
QandAPractice.this, questions,
R.layout.quizlayout, new String[]{TAG_QID,
TAG_TITLE, TAG_IMAGE,TAG_A,TAG_B,TAG_C,TAG_D,TAG_KEY,TAG_TIMER},
new int[]{R.id.quiz_id, R.id.quiz_content, R.id.quiz_image,R.id.quiz_A,R.id.quiz_B,
R.id.quiz_C,R.id.quiz_D,R.id.quiz_key,R.id.quiz_timer});
/* AtomicReference<ListAdapter> la =
new AtomicReference<>(new ListAdapter(getApplicationContext(), questions));*/
listView.setAdapter(adapter);
}
this is the Error fetch in debug logcat..
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setSelected(boolean)' on a null object reference
at com.example.jhan08.engineeringexclusivereviewer.QandAPractice.onCreate(QandAPractice.java:90)
at android.app.Activity.performCreate(Activity.java:6351)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1114)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2470)
I've read some thread that has the same issue like mine. They use adapter to fix the issue but still in my case this error still occur. Any help is much appreciated.
Do Your Selection after you set Your Adapter to the Listview
private void loadIntoListView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
//String[] question = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String id = obj.getString(TAG_QID);
String content = obj.getString(TAG_TITLE);
String image = obj.getString(TAG_IMAGE);
String a = obj.getString(TAG_A);
String b = obj.getString(TAG_B);
String c = obj.getString(TAG_C);
String d = obj.getString(TAG_D);
String key = obj.getString(TAG_KEY);
String timer = obj.getString(TAG_TIMER);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_QID,id);
map.put(TAG_TITLE,content);
map.put(TAG_IMAGE,image);
map.put(TAG_A,a);
map.put(TAG_B,b);
map.put(TAG_C,c);
map.put(TAG_D,d);
map.put(TAG_KEY,key);
map.put(TAG_TIMER,timer);
myqid.add(id);
questions.add(map);
}
// ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, question);
SimpleAdapter adapter = new SimpleAdapter(
QandAPractice.this, questions,
R.layout.quizlayout, new String[]{TAG_QID,
TAG_TITLE, TAG_IMAGE,TAG_A,TAG_B,TAG_C,TAG_D,TAG_KEY,TAG_TIMER},
new int[]{R.id.quiz_id, R.id.quiz_content, R.id.quiz_image,R.id.quiz_A,R.id.quiz_B,
R.id.quiz_C,R.id.quiz_D,R.id.quiz_key,R.id.quiz_timer});
/* AtomicReference<ListAdapter> la =
new AtomicReference<>(new ListAdapter(getApplicationContext(), questions));*/
listView.setAdapter(adapter);
listView.setSelection(0);
listView.getSelectedView().setSelected(true);
}
I think I got the main issue you have faced. You try to select an item before populating the list view. You need to set this after adapter added on the listview.
Add this lines after adding the adapter.
listView.setAdapter(adapter);
listView.setSelection(0);
listView.getSelectedView().setSelected(true);
or use
listView.setAdapter(adapter);
listView.setItemChecked(0, true)
This will show a toast message for first opening. This should be added after the adapter set.
Iterator myVeryOwnIterator = questions.get(0).keySet().iterator();
while(myVeryOwnIterator.hasNext()) {
String key=(String)myVeryOwnIterator.next();
String value=(String)meMap.get(key);
Toast.makeText(ctx, "Key: "+key+" Value: "+value, Toast.LENGTH_LONG).show();
}
I'm getting my coordinates from a Json, and I'm putting a marker on those coordinates and I do get them like 3 times it does show me the marker where it suppose to be but by the fourth time it changes to (0.0,0.0) and I don't know why. It doesn't throw any error it just changes the marker location to (0.0,0.0)
public class BusinessPremium extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
String longitude,latitude;
LatLng durango = new LatLng(0.0,0.0);
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business_premium);
SupportMapFragment supportFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
supportFragment.getMapAsync(this);
Bundle bundle=getIntent().getExtras();
int value=bundle.getInt("no");
new PlifRequestBase(BusinessPremium.this)
{
#Override
public JsonObject onHttpOk(JsonObject response) throws JSONException
{
JsonObject data, details, location, geolocation, more, phoneNumber;
JsonArray branches, phones;
data = response;
branches = data.get("branches").getAsJsonArray();
details = branches.get(0).getAsJsonObject();
location = details.get("location").getAsJsonObject();
geolocation = details.get("geolocation").getAsJsonObject();
phones = details.get("phones").getAsJsonArray();
more = phones.get(0).getAsJsonObject();
//phoneNumber = more.get("number").getAsJsonObject();
//ids = data.get("id").getAsInt();
final String name = data.get("name").getAsString();
final String description = data.get("description").getAsString();
final String category_image_cover = data.get("category_image_cover").getAsString();
final String category_image_logo = data.get("category_image_logo").getAsString();
final String street = location.get("street").getAsString();
final String number = location.get("number").getAsString();
final String neighborhood = location.get("neighborhood").getAsString();
final String zip = location.get("zip").getAsString();
final String municipality = location.get("municipality").getAsString();
final String numberP = more.get("number").getAsString();
latitude = geolocation.get("lat").getAsString();
longitude = geolocation.get("lng").getAsString();
durango=new LatLng(Double.parseDouble(latitude),Double.parseDouble(longitude));
final TextView txtName = (TextView) findViewById(R.id.nameBusiness);
final TextView txtDescription = (TextView) findViewById(R.id.description);
final ImageView txtCategory_image_cover = (ImageView) findViewById(R.id.coverBusiness);
final ImageView txtCategory_image_logo = (ImageView) findViewById(R.id.logoBusiness);
final TextView txtAddress = (TextView) findViewById(R.id.address);
final TextView txtPhone = (TextView) findViewById(R.id.phone);
BusinessPremium.this.runOnUiThread(new Runnable()
{
public void run()
{
txtName.setText(name);
txtDescription.setText(description);
Glide.with(BusinessPremium.this).load(category_image_cover).into(txtCategory_image_cover);
Glide.with(BusinessPremium.this).load(category_image_logo).into(txtCategory_image_logo);
txtAddress.setText(street + " " + number + "\n" + neighborhood + " " + zip + " " + municipality);
txtPhone.setText(numberP);
}
});
// Log.d("ID", String.valueOf(card));
Log.d("Nombre", name);
return data;
}
#Override
public void onHttpCreate(JsonObject response) throws JSONException
{
}
}.execute("businesses/" + String.valueOf(value), "GET");
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add marker in Durango and move the camera
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(durango ,17));
Log.d("adsadads",String.valueOf(durango));
if (mMap != null) {
Marker marker = mMap.addMarker(new MarkerOptions().position(durango).title("Marker in Durango"));
}
}
I have a listview where I have 50 elements being displayed. I have decided to paginate the view so on each part of the view there are 10 elements and then a next button is clicked to get to the next 10 elements. How can i set 10 data ? I follow this article
http://rakhi577.wordpress.com/2013/05/20/listview-pagination-ex-2/
Here is my code .Can you help me with my code or a link to a guide on how to implement this correctly?
public class MainActivity extends ListActivity {
Context context;
Button btnSearch ;
EditText txtSearch;
private ProgressDialog pDialog;
// URL to get contacts JSON
public int TOTAL_LIST_ITEMS = 50;
public int NUM_ITEMS_PAGE = 10;
private int noOfBtns;
private Button[] btns;
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// 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.activity_main);
btnSearch=(Button)findViewById(R.id.buttonSearch);
txtSearch=(EditText)findViewById(R.id.Searchtext);
}
public String gotourl()
{
final EditText txtSearch=(EditText)findViewById(R.id.Searchtext);
String ts=txtSearch.getText().toString();
String url = "http://latest.bloomapi.com/api/search?limit=50&offset=0&key1=last_name&op1=eq&value1="+ts;
return url ;
}
public void Searchfunction(View v)
{
Btnfooter();
//loadList(0);
CheckBtnBackGroud(0);
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 name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
private void Btnfooter()
{
int val = TOTAL_LIST_ITEMS%NUM_ITEMS_PAGE;
val = val==0?0:1;
noOfBtns=TOTAL_LIST_ITEMS/NUM_ITEMS_PAGE+val;
LinearLayout ll = (LinearLayout)findViewById(R.id.btnLay);
btns =new Button[noOfBtns];
for(int i=0;i<noOfBtns;i++)
{
btns[i] = new Button(this);
btns[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
btns[i].setText(""+(i+1));
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.addView(btns[i], lp);
final int j = i;
btns[j].setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
//loadList(j);
CheckBtnBackGroud(j);
}
});
}
}
private void CheckBtnBackGroud(int index)
{
for(int i=0;i<noOfBtns;i++)
{
if(i==index)
{
btns[index].setBackgroundDrawable(getResources().getDrawable(R.drawable.box_green));
btns[i].setTextColor(getResources().getColor(android.R.color.white));
}
else
{
btns[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
btns[i].setTextColor(getResources().getColor(android.R.color.black));
}
}
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected 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(gotourl(), ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray("result");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
Integer a = contacts.length();
Log.d("loop", a.toString());
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("npi");
String name = c.getString("first_name");
String email = c.getString("last_name");
//String address = c.getString(TAG_ADDRESS);
String gender = c.getString("type");
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put("npi", id);
contact.put("first_name", name);
contact.put("last_name", email);
//contact.put(TAG_PHONE_MOBILE, mobile);
contact.put("type", gender);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.d("ServiceHandler", "Couldn't get any data from the url");
}
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(
MainActivity.this, contactList,
R.layout.list_item, new String[] { "first_name", "last_name",
"type" }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}}
I change the code. When i click next button[like 2,3,4,5]. showing first page data. Here is my modified code.Any help Appreciated :
public class MainActivity extends ListActivity {
private TextView title;
Context context;
Button btnSearch ;
EditText txtSearch;
private ListView listview;
private ProgressDialog pDialog;
// URL to get contacts JSON
public int TOTAL_LIST_ITEMS = 50;
public int NUM_ITEMS_PAGE = 10;
private int noOfBtns;
private Button[] btns;
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// 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.activity_main);
btnSearch=(Button)findViewById(R.id.buttonSearch);
txtSearch=(EditText)findViewById(R.id.Searchtext);
title = (TextView)findViewById(R.id.title);
}
public String gotourl()
{
final EditText txtSearch=(EditText)findViewById(R.id.Searchtext);
String ts=txtSearch.getText().toString();
String url = "http://latest.bloomapi.com/api/search?limit=50&offset=0&key1=last_name&op1=eq&value1="+ts;
return url ;
}
public void Searchfunction(View v)
{
Btnfooter();
CheckBtnBackGroud(0);
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) {
if(position%2==0)
{
view.setBackgroundColor(Color.parseColor("#F4FA58"));
}else
{
view.setBackgroundColor(Color.parseColor("#DA81F5"));
}
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
private void Btnfooter()
{
int val = TOTAL_LIST_ITEMS%NUM_ITEMS_PAGE;
val = val==0?0:1;
noOfBtns=TOTAL_LIST_ITEMS/NUM_ITEMS_PAGE+val;
LinearLayout ll = (LinearLayout)findViewById(R.id.btnLay);
btns =new Button[noOfBtns];
for(int i=0;i<noOfBtns;i++)
{
btns[i] = new Button(this);
btns[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
btns[i].setText(""+(i+1));
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.addView(btns[i], lp);
final int j = i;
btns[j].setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
new GetContacts().execute();
CheckBtnBackGroud(j);
}
});
}
}
private void CheckBtnBackGroud(int index)
{
title.setText("Page "+(index+1)+" of "+noOfBtns);
for(int i=0;i<noOfBtns;i++)
{
if(i==index)
{
btns[index].setBackgroundDrawable(getResources().getDrawable(R.drawable.box_green));
btns[i].setTextColor(getResources().getColor(android.R.color.white));
}
else
{
btns[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
btns[i].setTextColor(getResources().getColor(android.R.color.black));
}
}
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected 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(gotourl(), ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
int number = 0;
int start = number * NUM_ITEMS_PAGE;
// looping through All Contacts
// Getting JSON Array node
contacts = jsonObj.getJSONArray("result");
// looping through All Contacts
//for (int i = 0; i < contacts.length(); i++) {
for(int i=start;i<(start)+NUM_ITEMS_PAGE;i++) {
Integer a = contacts.length();
Log.d("loop", a.toString());
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("npi");
String name = c.getString("first_name");
String email = c.getString("last_name");
String gender = c.getString("type");
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put("npi", id);
contact.put("first_name", name);
contact.put("last_name", email);
//contact.put(TAG_PHONE_MOBILE, mobile);
contact.put("type", gender);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.d("ServiceHandler", "Couldn't get any data from the url");
}
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(
MainActivity.this, contactList,
R.layout.list_item, new String[] { "first_name", "last_name",
"type" }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}}
Below is my code to show list view with pagination. There is two blue button for change pages.
You can customize according to you need.
Create UserCategory.java
package com.UserCategory;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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 android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
public class UserCategory extends Activity implements OnClickListener{
private final int PAGE_SIZE = 5;
private int StartingIndex = 0;
ArrayList<String> userClass=new ArrayList<String>();
int textlength=0;
private String lv_arr[];
private ListView lv1;
EditText searchText;
//Button Previous;
private String Machine[]={"Machine 1","Machine 2","Machine 3","Machine 4","Machine 5","Machine 6","Machine 7","Machine 8","Machine 9","Machine 10","Machine 11","Machine 12","Machine 1","Machine 2","Machine 3","Machine 4","Machine 5","Machine 6","Machine 7","Machine 8","Machine 9","Machine 10","Machine 11","Machine 12"};
ImageView next,Previous;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.main);
lv1=(ListView)findViewById(R.id.ListView01);
searchText=(EditText)findViewById(R.id.et_Serchlist);
next=(ImageView)findViewById(R.id.btn_next);
Previous=(ImageView)findViewById(R.id.btn_previous);
next.setOnClickListener(this);
Previous.setOnClickListener(this);
//parsing();
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , Machine));
changeListViewModel(0);
}
private void changelist(int startingIndex) {
if(startingIndex < 0) {
Previous=(ImageView)findViewById(R.id.btn_previous);
ImageView back=(ImageView)findViewById(R.id.btn_Whiteprevious);
back.setVisibility(1);
Previous.setVisibility(4);
startingIndex = 0;
}else if(startingIndex >= userClass.size())
startingIndex -= PAGE_SIZE;
StartingIndex = startingIndex;
int endingIndex = startingIndex + PAGE_SIZE;
System.out.println("ending index"+endingIndex);
if(StartingIndex!=0){
Previous=(ImageView)findViewById(R.id.btn_previous);
ImageView back=(ImageView)findViewById(R.id.btn_Whiteprevious);
back.setVisibility(4);
Previous.setVisibility(1);
}
if(endingIndex == userClass.size()){
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(1);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(4);
}
if(endingIndex != userClass.size()){
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(4);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(1);
}
if(endingIndex > userClass.size()) endingIndex = userClass.size();
try {
String[] subSet = getDataSubset1(startingIndex, endingIndex);
System.out.println("subSet array"+subSet);
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , subSet));
} catch (Exception e) {
e.printStackTrace();
}
}
private String[] getDataSubset1(int startingIndex, int endingIndex){
String[] changeList = new String[endingIndex - startingIndex];
int index = -1;
for(int x = startingIndex; x < endingIndex; x++)
changeList[++index] = userClass.get(x);
return changeList;
}
private void changeListViewModel(int startingIndex){
if(startingIndex < 0) {
Previous=(ImageView)findViewById(R.id.btn_previous);
ImageView back=(ImageView)findViewById(R.id.btn_Whiteprevious);
back.setVisibility(1);
Previous.setVisibility(4);
startingIndex = 0;
}
else if(startingIndex >= Machine.length){
startingIndex -= PAGE_SIZE;
}
System.out.println("strating"+startingIndex);
System.out.println("startingIndex"+startingIndex);
StartingIndex = startingIndex;
int endingIndex = startingIndex + PAGE_SIZE;
System.out.println("endingIndex"+endingIndex);
if(StartingIndex!=0)
{
Previous=(ImageView)findViewById(R.id.btn_previous);
ImageView back=(ImageView)findViewById(R.id.btn_Whiteprevious);
back.setVisibility(4);
Previous.setVisibility(1);
}
if(endingIndex == userClass.size()){
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(1);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(4);
}
if(endingIndex != userClass.size()){
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(4);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(1);
}
System.out.println("ending index"+endingIndex);
if(endingIndex > Machine.length) {
endingIndex = Machine.length;
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(1);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(4);
}
String[] subSet = getDataSubset(startingIndex, endingIndex);
System.out.println("subSet main array"+subSet.length);
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , subSet));
}
private String[] getDataSubset(int startingIndex, int endingIndex){
String[] toRet = new String[endingIndex - startingIndex];
int index = -1;
System.out.println("index"+index);
for(int x = startingIndex; x < endingIndex; x++)
toRet[++index] = Machine[x];
return toRet;
}
private void parsing() {
// TODO Auto-generated method stub
try {
URL url = new URL("http://10.10.1.100/DogEventsWebService/EventService.svc/categories/1");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("UserCategory");
Machine = new String[nodeList.getLength()];
for (int i = 0; i < nodeList.getLength(); i++)
{
Node node = nodeList.item(i);
Machine[i] = new String();
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("ClassDescription");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
Machine[i]=((Node) nameList.item(0)).getNodeValue();
}
System.out.println("after for loop Machine"+Machine);
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn_next:
textlength=searchText.getText().length();
System.out.println("nextbutton"+textlength);
if(textlength==0){
changeListViewModel(StartingIndex + PAGE_SIZE);
}else{
changelist(StartingIndex + PAGE_SIZE);
}
break;
case R.id.btn_previous:
textlength=searchText.getText().length();
if(textlength==0){
changeListViewModel(StartingIndex - PAGE_SIZE);
}else{
changelist(StartingIndex - PAGE_SIZE);
}
break;
default:
break;
}
}
}
create main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<View android:layout_height="35dp"
android:layout_width="fill_parent"
android:background="#ffffff"/>
<TextView android:id="#+id/tv_header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello"
android:layout_alignParentTop="true"
android:layout_marginLeft="0dp"
android:textSize="25dp"/>
<EditText
android:id="#+id/et_Serchlist"
android:layout_height="35dp"
android:paddingLeft="19dp"
android:layout_marginLeft="60dp"
android:layout_toRightOf="#+id/tv_header"
android:maxLength="20"
android:maxLines="1"
android:inputType="text"
android:hint="Search"
android:textColor="#ffffff"
android:background="#drawable/my_border"
android:layout_width="100dip"/>
<ListView
android:id="#+id/ListView01"
android:layout_width="fill_parent"
android:textSize="4px"
android:layout_below="#+id/tv_header"
android:layout_above="#+id/btn_previous"
android:layout_height="wrap_content" />
<View android:layout_height="55dp"
android:layout_below="#+id/ListView0"
android:layout_alignParentBottom="true"
android:layout_width="fill_parent"
android:background="#ffffff"/>
<ImageView
android:src="#drawable/grewprevious"
android:id="#+id/btn_Whiteprevious"
android:layout_width="wrap_content"
android:layout_marginLeft="12dp"
android:layout_marginBottom="6dp"
android:layout_below="#+id/ListView0"
android:visibility="invisible"
android:layout_alignParentBottom="true"
android:layout_height="wrap_content"/>
<ImageView
android:src="#drawable/right"
android:id="#+id/btn_grewforward"
android:layout_width="wrap_content"
android:layout_marginLeft="259dp"
android:layout_marginBottom="6dp"
android:layout_below="#+id/ListView0"
android:visibility="invisible"
android:layout_alignParentBottom="true"
android:layout_height="wrap_content"/>
<ImageView
android:src="#drawable/backward"
android:id="#+id/btn_previous"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="12dp"
android:layout_marginBottom="6dp"
android:layout_below="#+id/ListView0"
android:onClick="backButtonClicked"/>
<ImageView android:src="#drawable/forward"
android:id="#+id/btn_next"
android:layout_width="80dp"
android:layout_marginBottom="6dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_below="#+id/ListView0"
android:layout_marginLeft="249dp"
android:text="Next"
android:onClick="nextButtonClicked"/>
</RelativeLayout>
Create userlist.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="#+id/tv_className"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
</LinearLayout>
Add my_border.xml into Drawable folder:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="2dip" android:color="#ee777777" />
<solid android:color="#ee444444"/>
<padding
android:left="20dip"
android:top="2dip"
android:right="20dip"
android:bottom="2dip" />
<corners android:radius="15dip" />
![enter image description here][1]</shape>
If it give error for iamges then use any other images and run application.
Let me know it work for you.
Thanks
this is my code
{ public class MainActivity extends MapActivity {
private MapView mapView;
//test start
private static String url = "http://localhost/test/json_parser.php";
private static final String TAG_PLACE="place";
private static final String TAG_ID="id";
private static final String TAG_NAME_PLACE="name_place";
private static final String TAG_LATITUDE="latitude";
private static final String TAG_LONGITUDE="longitude";
private static final String TAG_PERSON="person";
private static final String TAG_DATE="date";
private static final String TAG_TIME="time";
JSONArray place = null;
String[] p_lat=null;
String[] p_lon=null;
String id;
String name_place;
String latitude;
String longitude;
String person;
String date;
String time;
//test end
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapView=(MapView)findViewById(R.id.mapview);
Drawable marker=getResources().getDrawable(R.drawable.marker);
marker.setBounds((int)(-marker.getIntrinsicWidth()/2),-marker.getIntrinsicHeight(), (int)(marker.getIntrinsicWidth()/2),0);
InterestingLocations funPlaces=new InterestingLocations(marker);
mapView.getOverlays().add(funPlaces);
GeoPoint pt=funPlaces.getCenterPt();
int latSpan=funPlaces.getLatSpanE6();
int lonSpan=funPlaces.getLonSpanE6();
Log.v("Overlays","Lat span is" + latSpan);
Log.v("Overlays","Lon span is" + lonSpan);
MapController mc=mapView.getController();
mc.setCenter(pt);
mc.zoomToSpan((int)(latSpan*1.5),(int)(lonSpan*1.5));
//test start
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
//System.out.println("Testingggg..." + json.length());
//test end
//test start
/*
try{
place = json.getJSONArray(TAG_PLACE);
for(int i=0;i<place.length();i++){
JSONObject c = place.getJSONObject(i);
id = c.getString(TAG_ID);
name_place = c.getString(TAG_NAME_PLACE);
latitude = c.getString(TAG_LATITUDE);
//p_lat[i]=latitude;
longitude = c.getString(TAG_LONGITUDE);
//p_lon[i]=longitude;
person = c.getString(TAG_PERSON);
date = c.getString(TAG_DATE);
time = c.getString(TAG_TIME);
}
}catch(JSONException e){
e.printStackTrace();
}/*
System.out.print(p_lat[0]);
System.out.print(p_lon[0]);
*/
//test end
}
public void myClickHandler(View target){
switch(target.getId()){
case R.id.zoomin:
mapView.getController().zoomIn();
break;
case R.id.zoomout:
mapView.getController().zoomOut();
break;
case R.id.sat:
mapView.setSatellite(true);
break;
case R.id.street:
mapView.setStreetView(true);
break;
case R.id.traffic:
mapView.setTraffic(true);
break;
case R.id.normal:
mapView.setSatellite(false);
mapView.setStreetView(false);
mapView.setTraffic(false);
break;
}
mapView.postInvalidateDelayed(2000);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
}
i am getting problem when i delete comment from
//System.out.println("Testingggg..." + json.length());
and when i delete comment from
/*
try{
place = json.getJSONArray(TAG_PLACE);
for(int i=0;i<place.length();i++){
JSONObject c = place.getJSONObject(i); .....
i tried many things i haven't succeed
the problem is in parsing json
and thanks for every one
this is my json file
{"place": [{"id":"1","name_place":"Jedeida","latitude":"36.502234","longitude":"9.561264","person":"ahmed","date":"2012-08-01","time":"07:45:50"},
{"id":"2","name_place":"jedeida","latitude":"36.502234","longitude":"9.561109","person":"ahmed","date":"2012-08-01","time":"07:46:30"},{"id":"3","name_place":"jedeida","latitude":"36.501676","longitude":"9.562135","person":"ahmed","date":"2012-08-01","time":"07:48:03"},{"id":"4","name_place":"jedeida","latitude":"36.50083","longitude":"9.563069","person":"ahmed","date":"2012-08-01","time":"07:50:05"},{"id":"5","name_place":"Tebourba","latitude":"36.51029","longitude":"9.553043","person":"ali","date":"2012-08-02","time":"06:05:41"},{"id":"6","name_place":"jedeida","latitude":"36.504886","longitude":"9.553918","person":"ali","date":"2012-08-02","time":"06:07:04"},{"id":"7","name_place":"jedeida","latitude":"36.503503","longitude":"9.555477","person":"ali","date":"2012-08-02","time":"06:09:23"},{"id":"8","name_place":"jedeida","latitude":"36.50211","longitude":"9.561287","person":"ali","date":"2012-08-02","time":"06:11:40"},{"id":"9","name_place":"jedeida","latitude":"36.501208","longitude":"9.562281","person":"ali","date":"2012-08-02","time":"06:13:26"},{"id":"10","name_place":"jedeida","latitude":"36.500477","longitude":"9.563136","person":"ali","date":"2012-08-02","time":"06:15:01"}]}
and this is a link to logcat file
enter link description here
You declare your string array p_lat & p_lon as null that's why your application get Force Closed. Your JSON parsing code is perfectly working.
You have to initialize string array with specific size as below.
String[] p_lat= new String[10];
String[] p_lon= new String[10];
You can also your ArrayList for better performance.
JSONObject c = place.getJSONObject(i);
are you sure that every index (i) is a jsonobject and not a other value/string ?
System.out.println("Testingggg..." + json.length());
try Integer.toString(json.length())
i am using wampserver and it appear that i must change
private static String url = "http://localhost/test/json_parser.php";
to
private static String url = "http://10.0.2.2/test/json_parser.php";
the problem seems to be caused by the incorrect address
this is why when you have problem don't forget to use log.d("","");
I am not able to properly extract out the latitude and longitude point set to draw route further. Can anybody get me the code to do so?
Thanks in advance
public class MapprojectActivity extends MapActivity {
/** Called when the activity is first created. */
static final String TAG_RESULTS = "results";
static final String TAG_GEO = "geometry";
static final String TAG_LOCATION = "location";
static final String TAG_LAT = "lat";
static final String TAG_LNG = "lng";
JSONArray res = null;
MapView mapView;
List<Overlay> mapOverlays;
Drawable drawable;
MyItemizedOverlay itemizedOverlay;
static String url = "http://maps.google.com/maps/api/geocode/json?address=guindy,+chennai,+IN&sensor=false";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
TextView lattv=(TextView)findViewById(R.id.lat);
TextView lngtv=(TextView)findViewById(R.id.lng);
JSONParstring jParser = new JSONParstring();
// getting JSON string from URL
try
{
JSONObject jobj = new JSONObject(json);
res = jobj.getJSONArray(TAG_RESULTS);
for(int i = 0; i < res.length(); i++){
JSONObject c = res.getJSONObject(i);
JSONObject loc = c.optJSONObject(TAG_GEO).optJSONObject(TAG_LOCATION);
String lat =loc.getString(TAG_LAT);
String lng = loc.getString(TAG_LNG);
lattv.setText(lat);
lngtv.setText(lng);
}
}
catch (JSONException e){ }
String i=(String) lattv.getText();
String j=(String) lngtv.getText();
double lat1 = Double.parseDouble(i);
double lng1 = Double.parseDouble(j);
mapView = (MapView) findViewById(R.id.map_view);
mapView.setBuiltInZoomControls(false);
mapOverlays = mapView.getOverlays();
drawable = getResources().getDrawable(R.drawable.mark1);
itemizedOverlay = new MyItemizedOverlay(drawable, mapView);
GeoPoint point = new GeoPoint((int)(lat1*1E6),(int)(lng1*1E6));
OverlayItem overlayItem = new OverlayItem(point, "Amy Jones",
"(checked in Lemon-tree with friends lisa wong, paul jones)");
itemizedOverlay.addOverlay(overlayItem);
mapOverlays.add(itemizedOverlay);
final MapController mc = mapView.getController();
mc.animateTo(point);
mc.setZoom(16);
// Integer i = Integer.valueOf((String) lattv.getText());
// Integer j = Integer.valueOf((String) lngtv.getText());
// // first overlay
}
protected boolean isRouteDisplayed() {
return false;
}
}
Here is to get Latitude/Longitude from JSON http://blog.synyx.de/2010/06/routing-driving-directions-on-android-part-1-get-the-route/
And this is how to draw a route http://blog.synyx.de/2010/06/routing-driving-directions-on-android-%E2%80%93-part-2-draw-the-route/
u should study it. i hope it'll help.