Menu
  • HOME
  • TAGS

Map Showing Blue Screen ,when drawing Path Between Two Places in Android

Tag: android,google-maps,dictionary

In android Google Map , I want to draw a path between two places.

When Iam Using Hardcoded latitude and Longitude Showing Perfectly.

Problem-1

But Latitude and Longitude Getting from other Intent Showing Blue Screen in Map

Then closing that page again opening its Showing path Between Two Points.

Problem-2

then Iam Changing the Latitude and longitude of Both Locations its Showing Previous Location Path.

Here Latitute and Longitude values Iam getting from Previous intent.

How to resolve it. I Have Added my Code

MainActivity .java

    public class MainActivity extends FragmentActivity implements OnInfoWindowClickListener{


        public double Latitude1_Current_double,Longitutde1_Current_double,Latitude1_Center_double,Longitude1_Center_double;

         private int zoomLevel = 11;

         LatLng origin1 = new LatLng(Latitude1_Current_double, Longitutde1_Current_double);
            LatLng dest1 = new LatLng(Latitude1_Service_double,Longitude1_Service_double);

            double lat1=Latitude1_Current_double;
            double lang1=Longitutde1_Current_double;
            double lat2=Latitude1_Center_double;
            double lang2=Longitude1_Center_double;


            GoogleMap map;
            ArrayList<LatLng> markerPoints;

             /*private int zoomLevel1 = 14;
             private int zoomLevel2 = 11;*/

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            Bundle extras = getIntent().getExtras();


            String Latitude1_Current_String=extras.getString("STRING_I_NEED_LATITUDE_Current");
            String Longitutde1_Current_String =extras.getString("STRING_I_NEED_LONGITUDE_Current");
            String Latitude1_ServiceCenter_String =extras.getString("STRING_I_NEED_LATITUDE_ServiceCenter");
            String Longitude1_ServiceCenter_String =extras.getString("STRING_I_NEED_LONGITUDE_ServiceCenter");

                Latitude1_Current_double = Double.parseDouble(Latitude1_Current_String);
                Longitutde1_Current_double = Double.parseDouble(Longitutde1_Current_String);
                Latitude1_ServiceCenter_double = Double.parseDouble(Latitude1_ServiceCenter_String);
                Longitude1_ServiceCenter_double = Double.parseDouble(Longitude1_ServiceCenter_String);


            Toast.makeText(getApplicationContext(), "Get Direction"+Latitude1_Current_double+","+Longitutde1_Current_double+
                    Latitude1_Center_double+","+Longitude1_Center_double,Toast.LENGTH_SHORT).show();



            // Initializing 
            markerPoints = new ArrayList<LatLng>();

            // Getting reference to SupportMapFragment of the activity_main
            SupportMapFragment fm = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);

            // Getting reference to Button
        //  Button btnDraw = (Button)findViewById(R.id.btn_draw);       

            // Getting Map for the SupportMapFragment
            map = fm.getMap();

            // Enable MyLocation Button in the Map
            map.setMyLocationEnabled(true);     



             map.addMarker(new MarkerOptions().position(origin1)
                     .title("User Current Location")
                     .snippet("LatLng"+"("+lat1+","+lang1+")")
                     .icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));

             map.addMarker(new MarkerOptions().position(dest1)
                     .title("Service Center Destination Location")
                     .snippet("LatLng"+"("+lat2+","+lang2+")")
                     .icon(BitmapDescriptorFactory
                      .defaultMarker(BitmapDescriptorFactory.HUE_RED)));


            map.moveCamera(CameraUpdateFactory.newLatLngZoom(origin1, zoomLevel));
            map.moveCamera(CameraUpdateFactory.newLatLngZoom(dest1, zoomLevel));

            markerPoints.add(origin1);
            markerPoints.add(dest1);


            // Getting URL to the Google Directions API
            String url = getDirectionsUrl(origin1, dest1);              

            DownloadTask downloadTask = new DownloadTask();

            // Start downloading json data from Google Directions API
            downloadTask.execute(url);




            // The map will be cleared on long click
            map.setOnMapLongClickListener(new OnMapLongClickListener() {

                @Override
                public void onMapLongClick(LatLng point) {
                    // Removes all the points from Google Map
                    map.clear();

                    // Removes all the points in the ArrayList
                    markerPoints.clear();

                }
            });




        }

        private String getDirectionsUrl(LatLng origin,LatLng dest){

            // Origin of route
            String str_origin = "origin="+origin.latitude+","+origin.longitude;

            // Destination of route
            String str_dest = "destination="+dest.latitude+","+dest.longitude;      

            // Sensor enabled
            String sensor = "sensor=false";         

            // Waypoints
            String waypoints = "";

            for(int i=2;i<markerPoints.size();i++)
            {
                LatLng point  = (LatLng) markerPoints.get(i);
                if(i==2)
                waypoints = "waypoints=";
                waypoints += point.latitude + "," + point.longitude + "|";
            }


            // Building the parameters to the web service
            String parameters = str_origin+"&"+str_dest+"&"+sensor+"&"+waypoints;

            // Output format
            String output = "json";

            // Building the url to the web service
            String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;


            return url;
        }

        /** A method to download json data from url */
        private String downloadUrl(String strUrl) throws IOException{
            String data = "";
            InputStream iStream = null;
            HttpURLConnection urlConnection = null;
            try{
                    URL url = new URL(strUrl);

                    // Creating an http connection to communicate with url 
                    urlConnection = (HttpURLConnection) url.openConnection();

                    // Connecting to url 
                    urlConnection.connect();

                    // Reading data from url 
                    iStream = urlConnection.getInputStream();

                    BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

                    StringBuffer sb  = new StringBuffer();

                    String line = "";
                    while( ( line = br.readLine())  != null){
                            sb.append(line);
                    }

                    data = sb.toString();

                    br.close();

            }catch(Exception e){
                    Log.d("Exception while downloading url", e.toString());
            }finally{
                    iStream.close();
                    urlConnection.disconnect();
            }
            return data;
         }



        // Fetches data from url passed
        private class DownloadTask extends AsyncTask<String, Void, String>{         

            // 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 = downloadUrl(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);            

                try
                {
                ParserTask parserTask = new ParserTask();

                // Invokes the thread for parsing the JSON data
                parserTask.execute(result);

            } 
            catch (Exception e)
            {
                e.printStackTrace();
                Log.i("Exceptoin in DownloadTask onPostExecute", "Errroor");
            }

            }       
        }

        /** A class to parse the Google Places in JSON format */
        private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{

            // Parsing the data in non-ui thread        
            @Override
            protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {

                JSONObject jObject; 
                List<List<HashMap<String, String>>> routes = null;                     

                try{
                    jObject = new JSONObject(jsonData[0]);
                    DirectionsJSONParser parser = new DirectionsJSONParser();

                    // Starts parsing data
                    routes = parser.parse(jObject);    
                }catch(Exception e){
                    e.printStackTrace();
                }
                return routes;
            }

            // Executes in UI thread, after the parsing process
            @Override
            protected void onPostExecute(List<List<HashMap<String, String>>> result)
            {

                try
                {

                ArrayList<LatLng> points = null;
                PolylineOptions lineOptions = null;

                // Traversing through all the routes
                for(int i=0;i<result.size();i++){
                    points = new ArrayList<LatLng>();
                    lineOptions = new PolylineOptions();

                    // Fetching i-th route
                    List<HashMap<String, String>> path = result.get(i);

                    // Fetching all the points in i-th route
                    for(int j=0;j<path.size();j++){
                        HashMap<String,String> point = path.get(j);                 

                        double lat = Double.parseDouble(point.get("lat"));
                        double lng = Double.parseDouble(point.get("lng"));
                        LatLng position = new LatLng(lat, lng); 

                        points.add(position);                       
                    }

                    // Adding all the points in the route to LineOptions
                    lineOptions.addAll(points);
                    lineOptions.width(5);
                    lineOptions.color(Color.BLUE);              
                }

                // Drawing polyline in the Google Map for the i-th route
                map.addPolyline(lineOptions);   

            } 
            catch (Exception e)
            {
                e.printStackTrace();
                Log.i("Exceptoin in  parsing process onPostExecute", "Errroor");
            }

            }           
        }   


        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }

        @Override
        public void onInfoWindowClick(Marker marker)
        {

            Intent intent = new Intent(this, NewActivity.class);
            intent.putExtra("snippet", marker.getSnippet());
            intent.putExtra("title", marker.getTitle());
            intent.putExtra("position", marker.getPosition());
            startActivity(intent);

        }   
    }

DirectionsJSONParser.java

import com.google.android.gms.maps.model.LatLng;

public class DirectionsJSONParser {

    /** Receives a JSONObject and returns a list of lists containing latitude and longitude */
    public List<List<HashMap<String,String>>> parse(JSONObject jObject){

        List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>();
        JSONArray jRoutes = null;
        JSONArray jLegs = null;
        JSONArray jSteps = null;    

        try {

            jRoutes = jObject.getJSONArray("routes");

            /** Traversing all routes */
            for(int i=0;i<jRoutes.length();i++){        
                jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
                List path = new ArrayList<HashMap<String, String>>();

                /** Traversing all legs */
                for(int j=0;j<jLegs.length();j++){
                    jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");

                    /** Traversing all steps */
                    for(int k=0;k<jSteps.length();k++){
                        String polyline = "";
                        polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
                        List<LatLng> list = decodePoly(polyline);

                        /** Traversing all points */
                        for(int l=0;l<list.size();l++){
                            HashMap<String, String> hm = new HashMap<String, String>();
                            hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
                            hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
                            path.add(hm);                       
                        }                               
                    }
                    routes.add(path);
                }
            }

        } catch (JSONException e) {         
            e.printStackTrace();
        }catch (Exception e){           
        }


        return routes;
    }   


    /**
     * Method to decode polyline points 
     * Courtesy : jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java 
     * */
    private List<LatLng> decodePoly(String encoded) {

        List<LatLng> poly = new ArrayList<LatLng>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;

        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng p = new LatLng((((double) lat / 1E5)),
                    (((double) lng / 1E5)));
            poly.add(p);
        }

        return poly;
    }
}

Best How To :

Figured out your problem:

    public double Latitude1_Current_double,Longitutde1_Current_double,Latitude1_Center_double,Longitude1_Center_double;

 private int zoomLevel = 11;

 LatLng origin1 = new LatLng(Latitude1_Current_double, Longitutde1_Current_double);
    LatLng dest1 = new LatLng(Latitude1_Service_double,Longitude1_Service_double);

    double lat1=Latitude1_Current_double;
    double lang1=Longitutde1_Current_double;
    double lat2=Latitude1_Center_double;
    double lang2=Longitude1_Center_double;

The variables origin1 and dest1 does not change even if you change lat1 and lang1, so map.addMarker(new MarkerOptions().position(origin1) will have origin1 =(0,0) the default value. You need to make sure that variables origin1 and dest1 are modified inside onCreate method so your markers does not placed in the middle of the ocean. Hope this clarifies. I've tested your code and as soon as I put origin1 and dest1 the correct lat/lng info in onCreate method, I've got desired result.

BitmapFont class does not have getBound(String) method

java,android,libgdx

After the API 1.5.6 we have a different way to get the String bound. try this GlyphLayout layout = new GlyphLayout(); layout.setText(bitmapFont,"text"); float width = layout.width; float height = layout.height; and it's not recommended to create new GlyphLayout on each frame, create once and use it. ...

Robolectric 3 : Load test specific resource

android,unit-testing,robolectric

Instead of putting the json in src/test/res/raw you might want to put it in src/test/resources/ and then you can use it ( with the latest build plugin and latest AS ) via getResource Be aware that there is a bug in older versions - you need to use AS from...

Android programming, draw a rectangle with specific coordinates

android

http://android.okhelp.cz/draw-rect-android-basic-example/ http://alvinalexander.com/android/how-to-draw-rectangle-in-android-view-ondraw-canvas canvas.drawColor(Color.CYAN); Paint p = new Paint(); // smooths p.setAntiAlias(true); p.setColor(Color.RED); p.setStyle(Paint.Style.STROKE); p.setStrokeWidth(4.5f); canvas.drawRect(10, 10, 30, 30, p); ...

Floating Action Button in Xamarin.Forms

android,xamarin,monodroid,xamarin.forms,floating-action-button

Before the official support library came out I ported the FAB over. There is now a Xamarin.Forms sample in my GitHub repo that you can use: https://github.com/jamesmontemagno/FloatingActionButton-for-Xamarin.Android...

Android set clickable text to go one fragment to another fragment

java,android,android-fragments,spannablestring

If LoginActivity is a fragment class then it would be okay is you use setOnClickListener on textview. But for fragment change you have to change Intent to fragmentTransaction, Use something like, textview.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getFragmentManager().beginTransaction().replace(R.id.container, new LoginActivity() ).addToBackStack("").commit(); }); But, if you want to...

android imageView scale

android,imageview,scale

Try this code. adjustViewBounds attribute makes the ImageView the same size as image that you put in it. <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:adjustViewBounds="true" /> If you need specific width or height change the wrap_content value....

how to use geocoder class to retrieve latitude and longitude through ajax

javascript,ajax,google-maps

Because of it's scope, your codeAddress javascript function is not visible for outer caller myLoop, as it is enclosed within myFunction, therefore you get the codeAddress is not defined. Try to rewrite your code similar to this (I have not tested, so it might not work right away, but you...

Problems implementing ViewHolder pattern

android,design-patterns

Try like this... public View getView(int poisition, View convertView , ViewGroup parent) { ViewHolder crimeHolder = null; //If we weren't given a view, inflate one if (convertView == null) { convertView = getActivity().getLayoutInflater().inflate(R.layout.list_item_crime, null); crimeHolder = new ViewHolder(); crimeHolder.titleTextView = (TextView)convertView.findViewById(R.id.listItemTitleTextView); crimeHolder.dateTextView = (TextView)convertView.findViewById(R.id.listItemDateTextView); crimeHolder.solvedCheckBox =...

Get element starting with letter from List

java,android,list,indexof

The indexOf method doesn't accept a regex pattern. Instead you could do a method like this: public static int indexOfPattern(List<String> list, String regex) { Pattern pattern = Pattern.compile(regex); for (int i = 0; i < list.size(); i++) { String s = list.get(i); if (s != null && pattern.matcher(s).matches()) { return...

how to add menu items to action bar in more than 30 activities

android,android-activity,android-studio,menu,menuitem

Option A A base Activity class that implements the logic for the menu items - in this case all 30 of your Activities should extend the base Activity. This approach has the serious limitation that it forces you to extend a class even though you may need to extend another...

Action view intent does not work

android,search-suggestion,custom-search-provider

Intent action names are case sensitive. Use this: android.intent.action.VIEW ...

Android Implicit Intent for Viewing a Video File

java,android,android-intent,uri,avd

Change your onClick method to below code. You should give the option to choose the external player. @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse("https://youtu.be/jxoG_Y6dvU8"), "video/*"); startActivity(Intent.createChooser(intent, "Complete action using")); } ...

Is there any way to use a pre-existing database from Xamarin without copying it from Assets?

android,xamarin,xamarin.forms

You don't want to use it from assets, even if you could, because assets is a compressed read only file, part of your installation. You can't write updates into it, which kills 90% of database use. And its inefficient for reading as its zipped up. So you really do need...

How to restrict file copying shared using Content Provider in Android?

android,security

No, sorry. If you hand bytes over to a third-party app, that third-party app can do what it wants with those bytes. So only solution is to use some in-app pdf reader right? This will not completely stop people from copying your PDFs. However, it will limit attacks to those...

error: cannot find symbol class AsyncCallWS Android

java,android,web-services

On the link you post, I see a class like below. Create this class in your project before using it. private class AsyncCallWS extends AsyncTask<String, Void, Void> { @Override protected Void doInBackground(String... params) { Log.i(TAG, "doInBackground"); getFahrenheit(celcius); return null; } @Override protected void onPostExecute(Void result) { Log.i(TAG, "onPostExecute"); tv.setText(fahren +...

Google map infowindow position

javascript,google-maps,events,infowindow

Two issues: There is a typo in your click listener code, javascript is case sensitive, infowindow and infoWindow are different objects, so you are not setting the position of the infowindow correctly. infowindow.open(map); infoWindow.setPosition(event.latLng); You are currently placing the infowindow at the place that is clicked infoWindow.setPosition(event.latLng);. If you want...

custom arraylist get distinct

java,android

It's not possible to do this using only the ArrayList. Either implement your own method which can be as simple as: private List<mystatistik> getAllUniqueEnemies(List<mystatistik> list){ List<mystatistik> uniqueList = new ArrayList<mystatistik>(); List<String> enemyIds = new ArrayList<String>(); for (mystatistik entry : list){ if (!enemyIds.contains(entry.getEnemyId())){ enemyIds.add(entry.getEnemyId()); uniqueList.add(entry); } } return uniqueList; } Or...

Blank screen on GridView

android,arrays,gridview

I executed ur code. Just add numberView.setTextColor(Color.BLACK); and it will work! :)...

Get current latitude and longitude android

java,android,gps,geolocation,location

See my post at http://gabesechansoftware.com/location-tracking/. The code you're using is just broken. It should never be used. The behavior you're seeing is one of the bugs- it doesn't handle the case of getLastLocation returning null, an expected failure. It was written by someone who kind of knew what he was...

Notification whenever a new topic is created on mosquitto

android,mqtt,mosquitto,libmosquitto

A topics is only "created" when something is published to it the first time. There is no mechanism to detect this apart from subscribing to a wildcard topic that would match all topics of interest and triggering processing when the first message is received on a given topic. In the...

echo json_encode after mysql_query failure

php,android

You can use an if on the result. If mysql_query() fails it returns false: $result = mysql_query(/*the query*/); if(!$result){ //Do stuff here, the query failed //json_encode() } else { //Query succeeded } Sidenote: mysql_* is deprecated, I highly recommend to switch to mysqli_* or PDO...

Android Espresso: Test running failed. No test results Empty test suite. Why?

android,android-espresso

Note that you are using the deprecated ActivityInstrumentationTestCase2 and that TestCases like ActivityInstrumentationTestCase2 or ServiceTestCase are deprecated in favor of ActivityTestRule or ServiceTestRule. So try switchwing to using the rules, which is actually pretty straightforward. Also, be sure to use the correct annotations. Check my other answer here to get...

how does android ImageView resize my image?

android

I'm not sure what are you trying to do, are you trying to have the imageview to adapt to your image's size or are you trying to have your image view at a fixed size? When the image is shown on a xhdpi screen will the image be scaled to...

Action Bar activity is closed

android,android-actionbar

Nag and Maisse already provided you proper answers but if these answers not working try this. Check in style.xml to know which theme are you using for your activity. <!-- Base application theme. --> <style name="AppTheme" parent="android:Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> </style> to <!-- Base application theme. -->...

Bluetooth pairing - how to show the simple Cancel/Pair dialog?

android,android-intent,bluetooth,android-bluetooth,bluetooth-oob

You are being prompted for entering the pin because that is what you are requesting in your pairingIntent. Instead of using pairingIntent.putExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, BluetoothDevice.PAIRING_VARIANT_PIN); pairingIntent.putExtra(BluetoothDevice.EXTRA_PAIRING_KEY, 1234); Use pairingIntent.putExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, PAIRING_VARIANT_PASSKEY_CONFIRMATION); As mentioned here, The user will be prompted to confirm the passkey displayed on the screen or an app will confirm the...

Twitter4j - cannot resolve method - setUsessl(boolean)

android,android-studio,twitter4j

Try to use the following configuration: ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setOAuthAuthenticationURL("https://api.twitter.com/oauth/request_token"); cb.setOAuthAccessTokenURL("https://api.twitter.com/oauth/access_token"); cb.setOAuthAuthorizationURL("https://api.twitter.com/oauth/authorize"); cb.setOAuthRequestTokenURL("https://api.twitter.com/oauth/request_token"); cb.setRestBaseURL("https://api.twitter.com/1.1/"); cb.setOAuthConsumerKey(consumerKey);...

Getting particular view from expandable listview

java,android,listview,android-fragments,expandablelistview

You shouldn't pass your view item form a fragment to an other. You should retrieve the object associated with your group view, pass this object to your second/edition fragment. You can use setTargetFragment(...) and onActivityResult(...) to send the modified text from your second to your first fragment. And then you...

Set value for Spinner with custom Adapter in Android

android,dynamic,android-arrayadapter,android-spinner

@Haresh Chhelana example is good, However if you want to show both name and code in spinner after selecting, check this out. List<Map<String, String>> items = new ArrayList<Map<String, String>>(); for (int i = 0; i < JA.length(); i++) { json = JA.getJSONObject(i); mapData = new HashMap<String, String>(); mapData.put("name", json.getString("Name")); mapData.put("code",...

Crop does not work for gallery images

android,image,crop

Try this Working code Buttonclick to take camera dialog.show(); Add this inside Oncreate() captureImageInitialization(); try this it will work // for camera private void captureImageInitialization() { try { /** * a selector dialog to display two image source options, from * camera ‘Take from camera’ and from existing files ‘Select...

Fixed element in android?

android,xml,android-fragments

You need a FrameLayout. In a FrameLayout, the children are overlapped on top of each other with the last child being at the topmost. activity_main.xml <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:fab="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent"...

Android String if-statement

java,android,string

Correct me if I'm wrong. If you're saying that your code looks like this: new Thread(new Runnable() { public void run() { // thread code if (ready.equals("yes")) { // handler code } // more thread code }).start(); // later on... ready = "yes"; And you're asking why ready = "yes"...

Why i get can not resolve method error in class android?

android,json

You didn't create setName() method in Person class. public class Person { private String name; private String country; private String twitter; //getters & setters.... public void setName(String pName) { this.name = pName; } public void getName() { return this.name; } } ...

Passing dynamic string resource to “setText()”

android

Try like this: Create a global variable like: private String name; then in "onCreateViewHolder" write like this: name= parent.getResources().getString(R.string.mac); now, in "onBindViewHolder" write like this: device.name.setText(name + data.macAddress); ...

Facebook Android API asks for additional permission

android,facebook,facebook-graph-api

Use the loginManager to add more permission. you can add it on click button or on create view or fragment LoginManager.getInstance().logInWithReadPermissions( fragmentOrActivity, Arrays.asList("user_friends")); You can also get AccessToken via following if needed after getting new permission AccessToken.getCurrentAccessToken() ...

why is Android app publishing taking several days [on hold]

android,google-play,publishing

here is detail provided by the google and for more details http://www.appmakr.com/blog/how-long-app-approved/ https://somethingididnotknow.wordpress.com/2014/03/11/how-long-does-it-take-for-the-google-play-store-to-publish-my-app-in-beta/ Android application approval process in playstore ...

Google map infowindow position on custom marker

javascript,css,google-maps,google-maps-api-3

Set the pixelOffset of the InfoWindow appropriately: From the documentation on InfoWindows pixelOffset | Type:Size | The offset, in pixels, of the tip of the info window from the point on the map at whose geographical coordinates the info window is anchored. If an InfoWindow is opened with an anchor,...

Keep HashMap with object data while app is idle - Android

android,android-activity

May be the activity is again loading that is onCreate() is called. So save the state and restore it. Use onSaveInstanceState() and onRestoreInstanceState(). Let me know whether it worked or not.

ACF Multiple Map Markers

wordpress,google-maps,google-maps-api-3,acf

You can create a custom query and loop through all locations. var locations = [ <?php $args = array( 'post_type' => 'your_post_type', 'posts_per_page' => -1 ); $locations = new WP_Query($args); if($locations->have_posts()){ while($locations->have_posts()){ the_post(); $loc = get_field('location') ?> ['<?php echo get_the_title(); ?>', <?php echo $loc[0]; ?>, <?php echo $loc[1]; ?>], <?php...

Android custom calendar view disable specific dates

android,calendarview

Include CalendarPickerView in your layout XML. <com.squareup.timessquare.CalendarPickerView android:id="@+id/calendar_view" android:layout_width="match_parent" android:layout_height="match_parent" /> In the onCreate of your activity/dialog or the onCreateView of your fragment, initialize the view with a range of valid dates as well as the currently selected date. Calendar nextYear = Calendar.getInstance(); nextYear.add(Calendar.YEAR, 1); CalendarPickerView calendar = (CalendarPickerView) findViewById(R.id.calendar_view);...

Contexts and callbacks from asynchronous tasks

android,android-fragments,asynchronous

getActivity() returning null is a perfectly valid scenario which you should expect as well. This happens because by creating anonymous Handler in your onCreateView you're referencing Fragment which was already detached from Activity (therefore getActivity() returns null). Same goes for your AsyncTask - if you're creating it as an anonymous...

Unfortunately, (My app) has stopped. Eclipse Android [duplicate]

java,android,eclipse,adt

In your MainActivity.java at line no 34 you are trying to initialize some widget that is not present in your xml layout which you have set it in your setContentView(R.layout.... That;s why you are geting nullpointerexception. EDIT: change your setContentView(R.layout.activity_main) to setContentView(R.layout.fragment_main)...

setOnClickListener error Null object

java,android

After super.onCreate(savedInstanceState); insert setContentView(R.layout.YourLayout); you need to make a request to a server in another thread. It might look like public class LoginTask extends AsyncTask<Void, Void, String>{ private String username; private String password; private Context context; public LoginTask(Context context, String username, String password) { this.username = username; this.password = password;...

Uncaught error: Invalid type for google table column

javascript,json,google-maps,google-visualization

You should change your row data.addColumn('String', 'sitecode'); to data.addColumn('string', 'sitecode'); (non capital "s" in "string"), of course this applies to all of your added columns. Javascript is case-sensitive....

Dagger 2 Custom Scope for each Fragment

android,android-fragments,dagger-2

Your understanding is correct. The named scopes allow you to communicate intention, but they all work the same way. For scoped provider methods, each Component instance will create 1 instance of the provided object. For unscoped provider methods, each Component instance will create a new instance of the provided object...

How to set speaker phone off when the app is killed by the “Recent App drawer”

android,android-audiomanager,ondestroy

Use a service like: public class FirstService extends Service { private AudioManager audioManager; @Override public IBinder onBind(Intent arg0) { return null; } @Override public void onDestroy() { super.onDestroy(); audioManager.setSpeakerphoneOn(false); //Turn of speaker } } public void onDestroy () Added in API level 1 Called by the system to notify a...

Is there any sdk to log exceptions, events and errors in production app?

android,logging,error-handling,sdk,production

Flurry analytics crashlytics They will give you the logs and errors in production app..I think this will suits you well...

Add a ListView or RecyclerView to new NavigationView

android,listview,recyclerview,navigationview

You can just nest the ListView or RecyclerView inside the NavigationView. <?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.DrawerLayout android:id="@+id/drawer_layout" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context=".MainActivity"> <FrameLayout...

adapter.notifyDataSetChanged() not working when I update ArrayList

android,android-listview

I have one way Create refresh method in your Adapter like public void refresh(ArrayList<Aviso> itemsw) { this.items = itemsw; notifyDataSetChanged(); } Now you just called this method from your Activity Aviso aviso = new Aviso(); aviso.setTitle("MMMMMMMMMMMMMMMMMMMMMM"); aviso.setDescription("Deskribapena"); aviso.setPubDate("Wed, 19 Mar 2016 12:40:00 GMT"); aviso.setDcDate("2016-03-19T12:40:00Z"); avisosList.add(aviso); adapter.refresh(avisosList); EDIT: To add the...

How to resolve Out of Memory Error on Bitmap in Android?

android,android-intent,android-activity,bitmap

use following method..... **************************************************** Bitmap bm = ShrinkBitmap(imagefile, 300, 300); image.setImageBitmap(bm); Bitmap ShrinkBitmap(String file, int width, int height) { BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options(); bmpFactoryOptions.inJustDecodeBounds = true; Bitmap bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions); int heightRatio =(int)Math.ceil(bmpFactoryOptions.outHeight/(float)height); int widthRatio =...

Can I install 2 or more Android SDK when using Eclipse

java,android,eclipse,sdk,versions

There shouldn't be any problem if you use the latest SDK version ; actually, this is recommended. However, make sure to set the correct "Target SDK", i.e. the highest android version you have successfully tested your app with, and the "Minimum Required SDK" as well....