I'm developing a app at the moment wich displayes a Map, your gps postition and a marker on this postition. Next Step is to recieve Data from a XML file. The XML I'm trying to use is http://webservice.recruit.co.jp/hotpepper/gourmet/v1/?key=899d70a29e983f4b&lat=33.58724&lng=130.3986&range=5&order=4
But poorly after launching the app (on a real device, newest version) the app terminates and displays nothing.
LogCat says FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.xmlparser/com.example.xmlparser.MainActivitz}: java.lang.nullPointerException
MainActivity.java
package com.example.xmlparser;
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
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 com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
public String url = "http://webservice.recruit.co.jp/hotpepper/gourmet/v1/?key=899d70a29e983f4b&lat=33.58724&lng=130.3986&range=5&order=4";
public EditText feldname, id;
public HandleXml obj;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
feldname = (EditText)findViewById(R.id.editText1);
id = (EditText)findViewById(R.id.editText2);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the location provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null)
{
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
}
else
{
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
float lat1 = (float) (location.getLatitude()); //Getting the position
float lng1 = (float) (location.getLongitude());
GoogleMap mMap;
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.fragment1)).getMap();
mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat1, lng1))
.title("Your Position"));
LatLng bounds = new LatLng(lat1, lng1);
CameraUpdate cu = CameraUpdateFactory.newLatLng(bounds);
mMap.moveCamera(cu);
}
//Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
float lat = (float) (location.getLatitude()); //Getting the ' ''
float lng = (float) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
public void open(View view)
{
feldname.setText(url);
obj = new HandleXml(url);
obj.fetchXML();
while(obj.parsingComplete);
feldname.setText(obj.getFeldName());
id.setText(obj.getId());
}
}
HandleXml.java
package com.example.xmlparser;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
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.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class HandleXml {
private String feldname = "name";
private String id = "id";
private String urlString = null;
private XmlPullParserFactory xmlFactoryObject;
public volatile boolean parsingComplete = true;
public HandleXml(String url)
{
this.urlString = url;
}
public String getFeldName()
{
return feldname;
}
public String getId()
{
return id;
}
public void parseXMLAndStoreIt(XmlPullParser myParser)
{
int event;
String text=null;
try
{
event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT)
{
String name=myParser.getName();
switch (event)
{
case XmlPullParser.START_TAG:
break;
case XmlPullParser.TEXT:
text = myParser.getText();
break;
case XmlPullParser.END_TAG:
if(name.equals("name_kana"))
{
feldname = text;
}
else if(name.equals("id"))
{
id =text;// myParser.getAttributeValue(null,"value");
}
else
{}
break;
}
event = myParser.next();
}
parsingComplete = false;
} catch (Exception e) {
e.printStackTrace();
}
}
public void fetchXML()
{
Thread thread = new Thread(new Runnable()
{
#Override
public void run()
{
try
{
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection)
url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
InputStream stream = conn.getInputStream();
xmlFactoryObject = XmlPullParserFactory.newInstance();
XmlPullParser myparser = xmlFactoryObject.newPullParser();
myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES
, false);
myparser.setInput(stream, null);
parseXMLAndStoreIt(myparser);
stream.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
});
thread.start();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.xmlparser"
android:versionCode="1"
android:versionName="1.0" >
<permission
android:name="com.example.map.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-sdk
android:minSdkVersion="12"
android:targetSdkVersion="18" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<uses-permission android:name="com.vogella.android.locationapi.maps.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" android:debuggable="true">
<uses-library android:name="com.google.android.maps" />
<activity
android:name="com.example.xmlparser.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyC3DipaFNo1EC44rZ8N1AJKVAiUCNOtqZw"/>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
I really hope one of you can tell me whats wrong with this code as it was working perfectly fine with only the map on it's own and the parser as an own program.
Related
I ask for help, there is a class for setting live wallpapers on android. Everything seems to be connected and should work as it should, but nothing works. Tell me what's wrong?
onCreateEngine is not called for some reason at startActivity.
package com.atticpic;
import android.os.Environment;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import android.media.ThumbnailUtils;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.Promise;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.WallpaperManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.service.wallpaper.WallpaperService;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceHolder;
import android.app.PendingIntent;
import android.app.Activity;
public class ReactVideoWallpaperModule extends ReactContextBaseJavaModule {
Context context;
private File file;
private VideoWallpaper mVideoWallpaper;
public ReactVideoWallpaperModule(ReactApplicationContext reactContext) {
super(reactContext);
context = reactContext.getApplicationContext();
}
#Override
public String getName() {
return "ReactVideoWallpaper";
}
#ReactMethod
void setWallpaperVideo(final String videoUri) {
mVideoWallpaper = new VideoWallpaper();
file = new File(videoUri);
if (!file.exists()) {
Log.i( null, "File not found: " + file);
}
mVideoWallpaper.setToWallPaper(context, file.getAbsolutePath());
}
public class VideoWallpaper extends WallpaperService {
#Override
public Engine onCreateEngine() {
Log.i( TAG, "( START VideoEngine )");
return new VideoWallpagerEngine();
}
private final String TAG = VideoWallpaper.class.getName();
private String sVideoPath;
protected int playheadTime = 0;
public void setToWallPaper(Context context,String videoPath) {
try {
context.clearWallpaper();
} catch (IOException e) {
e.printStackTrace();
}
sVideoPath = videoPath;
Intent intent = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
//intent.setAction(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT);
//intent.setClass(context, VideoWallpaper.class);
intent.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT, new ComponentName(context, VideoWallpaper.class));
//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
class VideoWallpagerEngine extends Engine {
private final String TAG = getClass().getSimpleName();
private MediaPlayer mediaPlayer;
public VideoWallpagerEngine() {
super();
Log.i( TAG, "( VideoEngine )");
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(sVideoPath);
mediaPlayer.setLooping(true);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onCreate(SurfaceHolder surfaceHolder) {
Log.i( TAG, "onSurfaceCreated" );
super.onCreate(surfaceHolder);
}
#Override
public void onDestroy() {
Log.i( TAG, "onSurfaceCreated" );
super.onDestroy();
}
#Override
public void onVisibilityChanged(boolean visible) {
Log.i( TAG, "onSurfaceCreated" );
if (visible){
mediaPlayer.start();
}else {
mediaPlayer.pause();
}
}
#Override
public void onSurfaceCreated(SurfaceHolder holder) {
Log.i( TAG, "onSurfaceCreated" );
mediaPlayer.setSurface(holder.getSurface());
mediaPlayer.start();
}
#Override
public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.i( TAG, "onSurfaceCreated" );
super.onSurfaceChanged(holder, format, width, height);
}
#Override
public void onSurfaceDestroyed(SurfaceHolder holder) {
Log.i( TAG, "( INativeWallpaperEngine ): onSurfaceDestroyed" );
playheadTime = mediaPlayer.getCurrentPosition();
mediaPlayer.reset();
mediaPlayer.release();
}
}
}
}
Call to react native
const DownloadImage = async (item) => { const result = await NativeModules.ReactVideoWallpaper.setWallpaperVideo(dirFile); }
There is a video file, there are no errors, tell me what is wrong?
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
<application
android:name=".MainApplication"
android:label="#string/app_name"
android:icon="#mipmap/ic_launcher"
android:roundIcon="#mipmap/ic_launcher_round"
android:allowBackup="true"
android:requestLegacyExternalStorage="true"
android:usesCleartextTraffic="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.atticpic.ReactVideoWallpaperModule.VideoWallpaper"
android:exported="true"
android:label="#string/app_name"
android:permission="android.permission.BIND_WALLPAPER"
android:process=":wallpaper">
<intent-filter>
<action android:name="android.service.wallpaper.WallpaperService" />
</intent-filter>
<meta-data
android:name="android.service.wallpaper"
android:resource="#xml/livewallpaper" />
</service>
</application>
It is expected to be completed and as a result of success, the installation of video wallpapers is expected.
I searched the web for examples displaying pdf documents within a app. Additionally i searched for a Downloader class because i want to load the pdf from the internet. After execution it just displays blank PDF page.
MainActivity.java just sends the pdf link to the DisplayPDF.java Activity:
package com.example.pdfviewevaluation;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "com.example.pdfviewevaluation.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, DisplayPDF.class);
String url = "pdf link";
intent.putExtra(EXTRA_MESSAGE, url);
startActivity(intent);
}
}
DisplayPDF.java creates the Folder and PDF in the cache directory. Then it starts the Downloader with the pdf link and directory. Finally it should just show the pdf:
package com.example.pdfviewevaluation;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class DisplayPDF extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_pdf);
String pdfURL = getIntent().getStringExtra(MainActivity.EXTRA_MESSAGE);
File folder = new File(this.getCacheDir(), "pdf");
folder.mkdir();
File file = new File(folder, "Read.pdf");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
Downloader dl = new Downloader(pdfURL, file);
try {
dl.execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
showPdf();
}
public void showPdf() {
File file = new File(this.getCacheDir()+"/pdf/Read.pdf");
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = FileProvider.getUriForFile(this.getApplicationContext(), this.getApplicationContext().getPackageName() + ".provider", file);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
}
}
Downloader.java connects to the pdf page and download the pdf from the given link to the desired directory:
package com.example.pdfviewevaluation;
import android.os.AsyncTask;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Downloader extends AsyncTask<Void,Void,Void> {
private String fileURL;
private File directory;
public Downloader(String fileURL, File directory)
{
this.fileURL = fileURL;
this.directory = directory;
}
protected Void doInBackground(Void... params) {
try {
FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
int i = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
After many hours spending on my problem i searched for another solution on YouTube. These one are showing the solution:
https://www.youtube.com/watch?v=pGlqHeB5hdk
https://www.youtube.com/watch?v=8YPJCOxiklQ
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.downloadingfiles">
<uses-sdk android:minSdkVersion="21"
android:targetSdkVersion="22" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java:
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.pdf.PdfRenderer;
import android.net.Uri;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.webkit.URLUtil;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
public class MainActivity extends AppCompatActivity {
String myUrl = "http://www.orimi.com/pdf-test.pdf";
private ImageView imageView;
private int currentPage = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(myUrl));
request.setTitle("File download.");
request.setDescription("File is being downloaded...");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
String nameOfFile = URLUtil.guessFileName(myUrl, null, MimeTypeMap.getFileExtensionFromUrl(myUrl));
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, nameOfFile);
DownloadManager manager = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
BroadcastReceiver onComplete=new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
render();
}
};
/**Called when the user clicks the "Next" button defined in activity_main.xml */
public void nextPage(View view) {
currentPage++;
render();
}
/**Called when the user clicks the "Previous" button defined in activity_main.xml */
public void previousPage(View view) {
currentPage--;
render();
}
private void render(){
try{
imageView = (ImageView) findViewById(R.id.image);
int REQ_WIDTH = imageView.getWidth();
int REQ_HEIGHT = imageView.getHeight();
Bitmap bitmap = Bitmap.createBitmap(REQ_WIDTH, REQ_HEIGHT, Bitmap.Config.ARGB_4444);
String nameOfFile = URLUtil.guessFileName(myUrl, null, MimeTypeMap.getFileExtensionFromUrl(myUrl));
File file = new File("/sdcard/Download/"+nameOfFile);
PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));
if(currentPage < 0){
currentPage = 0;
}else if(currentPage >= renderer.getPageCount()){
currentPage = renderer.getPageCount() - 1;
}
Matrix m = imageView.getImageMatrix();
Rect rect = new Rect(0, 0, REQ_WIDTH, REQ_HEIGHT);
renderer.openPage(currentPage).render(bitmap, rect, m, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
imageView.setImageMatrix(m);
imageView.setImageBitmap(bitmap);
imageView.invalidate();
} catch (Exception e){
e.printStackTrace();
}
}
}
Please help, as the code below that should send a GET request does not work.
Behaviour: after tapping the button it writes "Running", then uses some traffic, then after some time hangs and crashes.
My goal is to send HTTP GET and handle the response as a string. I have tried a lot of options but they failed.
I'll greatly appreciate any working way of HTTP requests that NOT run in the UI (main) thread. Requests in the main thread are no more allowed and throw a networkonmainthreadexception.
Thanks in advance!
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
MainActivity.java (I'll delete waste imports later):
package com.aohdhgdsb.helloworld;
import android.app.DownloadManager;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ImageView;
import android.widget.Toast;
import android.os.Handler;
import android.widget.TextView.OnEditorActionListener;
import android.view.inputmethod.EditorInfo;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import android.os.AsyncTask;
import java.io.InputStream;
import java.net.URLConnection;
public class MainActivity extends AppCompatActivity {
public EditText Edit1;
public EditText Edit2;
public TextView Text1;
public ImageView Img1;
public Button But1;
#Override
protected void onCreate(Bundle savedInstanceState) {
showToast("Hi. I have started!\r\nv6");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void showToast(String toast){
try {
Toast toast2 = Toast.makeText(getApplicationContext(),
"" + toast,
Toast.LENGTH_SHORT);
//toast2.setGravity(Gravity.TOP, 0, 0);
toast2.show();
} catch (Throwable e) {
showToast("Error while showing the toast!");
/*
Toast toast3 = Toast.makeText(getApplicationContext(),
"TOAST ERR: " + e,
Toast.LENGTH_LONG);
toast3.show();
*/
}
}
public String readStream(InputStream is) {
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int i = is.read();
while(i != -1) {
bo.write(i);
i = is.read();
}
return bo.toString();
} catch (IOException e) {
return "";
}
}
public void Go(View v) {
handleResponse("Running...");
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
//******************************************
try{
URL url = new URL("http://example.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try{
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
handleResponse(readStream(in));
} catch (Throwable e) {showToast("ERROR7: " + e);}
finally {
urlConnection.disconnect();
}
} catch (Throwable e) {
showToast("ERROR6: " + e);
}
//****************************************
}
});
thread.start();
}
public void handleResponse(String str){
Edit2 = (EditText) findViewById(R.id.editText2);
Edit2.setText(str);
}
}
Part of activity_main.xml:
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go!"
android:id="#+id/button3"
android:layout_gravity="center_horizontal"
android:onClick="Go" />
<EditText
android:layout_width="match_parent"
android:layout_height="256dp"
android:id="#+id/editText2"
android:layout_gravity="center_horizontal"
android:layout_weight="8.25"
android:text="Nothing" />
Try using AsyncTask, simple example:
public class MyAsyncTask extends AsyncTask<String, Void, String> {
Context context;
//Constructor
public AsyncWS(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//BEFORE Execution
//initialize a ProgressDialog, ...
}
#Override
protected String doInBackground(String... args) {
//MAke all the http calls
return result; //This is going to be sent to onPostExecute
}
#Override
protected void onPostExecute(String result) {
//After Execution, here you are working again in the main thread
super.onPostExecute(result);
//Make toasts, change views, stop ProgressDialogs
}
}
Call it with:
MyAsyncTask myAsyncTask = new MyAsyncTask (context);
myAsyncTask.execute(args); //args = String[]
Reference: http://developer.android.com/guide/components/processes-and-threads.html#WorkerThreads
When I try to start my IntenetService I get no errors, but it never hits the breakpoint in onHandleIntent
MainActivity.java
package com.peterchappy.filewatcher.activities;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.peterchappy.filewatcher.R;
import com.peterchappy.filewatcher.services.FileDownloadService;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class MainActivity extends Activity {
public static final String INTENT_EXTRA_FILE_URL = "URL";
private FileDownloadBroadcastReceiver broadcastReceiver;
private Button go;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
go = (Button) findViewById(R.id.go);
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
downloadFile("http://www.reddit.com/");
}
});
}
#Override
protected void onStart() {
super.onStart();
broadcastReceiver = new FileDownloadBroadcastReceiver();
registerReceiver(broadcastReceiver, new IntentFilter(FileDownloadService.FILE_DOWNLOADED));
}
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(broadcastReceiver);
}
private void downloadFile(String text) {
Intent intent = new Intent(this, FileDownloadService.class);
intent.putExtra(INTENT_EXTRA_FILE_URL, text);
this.startService(intent);
}
private void readFileAndDisplayContent(String fileName) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(openFileInput(fileName)));
StringBuilder content = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
content.append(line).append("\n");
}
reader.close();
System.out.println(content.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
private class FileDownloadBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String localFileName = intent.getStringExtra(FileDownloadService.INTENT_LOCAL_FILE_NAME);
readFileAndDisplayContent(localFileName);
}
}
}
FileDownloadService.java
package com.peterchappy.filewatcher.services;
import android.app.IntentService;
import android.content.Intent;
import com.peterchappy.filewatcher.activities.MainActivity;
import com.peterchappy.filewatcher.helpers.FileDownloader;
public class FileDownloadService extends IntentService {
public static final String INTENT_LOCAL_FILE_NAME = "local_file_name";
public static final String FILE_DOWNLOADED = "FILE_DOWNLOADED";
public FileDownloadService() {
super("FILE_DOWNLOAD_SERVICE");
}
#Override
protected void onHandleIntent(Intent intent) {
FileDownloader fileDownloader = new FileDownloader(this);
String localFileName = fileDownloader.downloadFile(intent.getStringExtra(MainActivity.INTENT_EXTRA_FILE_URL));
Intent resultIntent = new Intent(FILE_DOWNLOADED);
resultIntent.putExtra(INTENT_LOCAL_FILE_NAME, localFileName);
sendBroadcast(resultIntent);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".activities.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<service android:name=".filewatcher.services.FileDownloadService"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Ok, now I think I see it in your manifest. <service> tag is outside <application> tag, try moving it inside.
I've follow tutorial to create simple android map, here's my source code (MainActivity.java) :
package com.tugas.akhir;
import java.util.List;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.CancelableCallback;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import com.tugas.akhir.R;
import com.tugas.akhir.googlemaps.GMapV2Direction;
import com.tugas.akhir.googlemaps.GetRotueListTask;
import com.tugas.akhir.googlemaps.GMapV2Direction.DirecitonReceivedListener;
import android.support.v4.app.FragmentActivity;
/**
*
* #author Omer F. KAPLAN
*
*/
public class MapActivity extends FragmentActivity
implements OnClickListener, OnInfoWindowClickListener,
DirecitonReceivedListener {
private GoogleMap mMap;
private Button btnDirection;
LatLng startPosition;
String startPositionTitle;
String startPositionSnippet;
LatLng destinationPosition;
String destinationPositionTitle;
String destinationPositionSnippet;
ToggleButton tbMode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startPosition = new LatLng(41.036896, 28.985490);
startPositionTitle = "Taksim Square";
startPositionSnippet = "Istanbul / Turkey";
destinationPosition = new LatLng(41.005921, 28.977737);
destinationPositionTitle = "Sultanahmet Mosque, Istanbul";
destinationPositionSnippet = "Istanbul / Turkey";
btnDirection = (Button) findViewById(R.id.btnDirection);
btnDirection.setOnClickListener(this);
tbMode = (ToggleButton) findViewById(R.id.tbMode);
tbMode.setChecked(true);
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the
// map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
mMap.setMyLocationEnabled(true);
mMap.setIndoorEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setAllGesturesEnabled(true);
mMap.setOnInfoWindowClickListener(this);
}
public void clearMap() {
mMap.clear();
}
#Override
public void onClick(View v) {
if (v == btnDirection) {
clearMap();
MarkerOptions mDestination = new MarkerOptions()
.position(destinationPosition)
.title(destinationPositionTitle)
.snippet(destinationPositionSnippet)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin1));
MarkerOptions mStart = new MarkerOptions()
.position(startPosition)
.title(startPositionTitle)
.snippet(startPositionSnippet)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin2));
mMap.addMarker(mDestination);
mMap.addMarker(mStart);
if (tbMode.isChecked()) {
new GetRotueListTask(MapActivity.this, startPosition,
destinationPosition, GMapV2Direction.MODE_DRIVING, this)
.execute();
} else {
new GetRotueListTask(MapActivity.this, startPosition,
destinationPosition, GMapV2Direction.MODE_WALKING, this)
.execute();
}
}
}
#Override
public void OnDirectionListReceived(List<LatLng> mPointList) {
if (mPointList != null) {
PolylineOptions rectLine = new PolylineOptions().width(10).color(
Color.RED);
for (int i = 0; i < mPointList.size(); i++) {
rectLine.add(mPointList.get(i));
}
mMap.addPolyline(rectLine);
CameraPosition mCPFrom = new CameraPosition.Builder()
.target(startPosition).zoom(15.5f).bearing(0).tilt(25)
.build();
final CameraPosition mCPTo = new CameraPosition.Builder()
.target(destinationPosition).zoom(15.5f).bearing(0)
.tilt(50).build();
changeCamera(CameraUpdateFactory.newCameraPosition(mCPFrom),
new CancelableCallback() {
#Override
public void onFinish() {
changeCamera(CameraUpdateFactory
.newCameraPosition(mCPTo),
new CancelableCallback() {
#Override
public void onFinish() {
LatLngBounds bounds = new LatLngBounds.Builder()
.include(startPosition)
.include(
destinationPosition)
.build();
changeCamera(
CameraUpdateFactory
.newLatLngBounds(
bounds, 50),
null, false);
}
#Override
public void onCancel() {
}
}, false);
}
#Override
public void onCancel() {
}
}, true);
}
}
/**
* Change the camera position by moving or animating the camera depending on
* input parameter.
*/
private void changeCamera(CameraUpdate update, CancelableCallback callback,
boolean instant) {
if (instant) {
mMap.animateCamera(update, 1, callback);
} else {
mMap.animateCamera(update, 4000, callback);
}
}
#Override
public void onInfoWindowClick(Marker selectedMarker) {
if (selectedMarker.getTitle().equals(startPositionTitle)) {
Toast.makeText(this, "Marker Clicked: " + startPositionTitle,
Toast.LENGTH_LONG).show();
} else if (selectedMarker.getTitle().equals(destinationPositionTitle)) {
Toast.makeText(this, "Marker Clicked: " + destinationPositionTitle,
Toast.LENGTH_LONG).show();
}
selectedMarker.hideInfoWindow();
}
#Override
protected void onResume() {
super.onResume();
}
}
Beside MainActivity.java, i write down GetRotueListTask.java, here's source code :
package com.tugas.akhir.googlemaps;
import java.util.List;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.widget.Toast;
import com.google.android.gms.maps.model.LatLng;
import com.tugas.akhir.googlemaps.GMapV2Direction.DirecitonReceivedListener;
public class GetRotueListTask extends AsyncTask<Void, Void, Void> {
private final Context mContext;
GMapV2Direction mGMDirection = new GMapV2Direction();
LatLng fromPosition;
LatLng toPosition;
List<LatLng> mPointList;
private ProgressDialog dialog;
private int mDirectionMode;
DirecitonReceivedListener mListener;
public GetRotueListTask(Context context, LatLng fromPosition,
LatLng toPosition, int mDirectionMode,
DirecitonReceivedListener mListener) {
this.mContext = context;
this.fromPosition = fromPosition;
this.toPosition = toPosition;
this.mDirectionMode = mDirectionMode;
this.mListener = mListener;
}
#Override
protected Void doInBackground(Void... params) {
mGMDirection.setParams(fromPosition, toPosition, mDirectionMode);
mPointList = mGMDirection.getPointList(this.mContext);
return null;
}
#Override
protected void onPostExecute(Void result) {
if (dialog.isShowing()) {
dialog.dismiss();
}
if (mPointList != null) {
mListener.OnDirectionListReceived(mPointList);
} else {
Toast.makeText(this.mContext, "Error downloading direction!",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onPreExecute() {
ConnectivityManager conMgr = (ConnectivityManager) mContext
.getApplicationContext().getSystemService(
Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnectedOrConnecting()) {
// Background: Connected to internet
dialog = new ProgressDialog(mContext);
dialog.setMessage("Downloading directions...");
dialog.show();
} else {
this.cancel(true);
Toast.makeText(mContext, "Not connected to internet!",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCancelled() {
super.onCancelled();
}
}
After that i according tutorial, i write GMapV2Direction.java :
package com.tugas.akhir.googlemaps;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
import com.google.android.gms.maps.model.LatLng;
/**
* #author KAPLANDROID
*/
public class GMapV2Direction {
LatLng src, dest;
public List<LatLng> pointToDraw;
public static final int MODE_DRIVING = 1;
public static final int MODE_WALKING = 2;
public int mDirectionMode;
public void setParams(LatLng src, LatLng dest, int mMode) {
this.src = src;
this.dest = dest;
this.mDirectionMode = mMode;
}
public List<LatLng> getPointList(Context mContext) {
if (src != null || dest != null) {
// connect to map web service
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(makeUrl(src, dest));
HttpResponse response;
try {
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = null;
is = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
reader.close();
String result = sb.toString();
JSONObject jsonObject = new JSONObject(result);
JSONArray routeArray = jsonObject.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes
.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
pointToDraw = decodePoly(encodedString);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return pointToDraw;
} else {
throw new NullPointerException(
"Source or Destination coordinate is null. You must call \"setParams(LatLng,LatLng)\" method first!");
}
}
private List<LatLng> decodePoly(String poly) {
int len = poly.length();
int index = 0;
List<LatLng> decoded = new LinkedList<LatLng>();
int lat = 0;
int lng = 0;
while (index < len) {
int b;
int shift = 0;
int result = 0;
do {
b = poly.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 = poly.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
decoded.add(new LatLng((lat / 1E5), (lng / 1E5)));
}
return decoded;
}
private String makeUrl(LatLng src, LatLng dest) {
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.googleapis.com/maps/api/directions/json");
// from
urlString.append("?origin=");
urlString.append(Double.toString((double) src.latitude));
urlString.append(",");
urlString.append(Double.toString((double) src.longitude));
// to
urlString.append("&destination=");
urlString.append(Double.toString((double) dest.latitude));
urlString.append(",");
urlString.append(Double.toString((double) dest.longitude));
urlString.append("&sensor=false&units=metric");
if (mDirectionMode == MODE_DRIVING) {
urlString.append("&mode=driving");
} else if (mDirectionMode == MODE_WALKING) {
urlString.append("&mode=walking");
}
Log.d("Request URL", "URL=" + urlString.toString());
return urlString.toString();
}
public interface DirecitonReceivedListener {
public void OnDirectionListReceived(List<LatLng> mPointList);
}
}
Then i write a layout like this :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:orientation="vertical" >
<fragment
android:id="#+id/map"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_margin="5dp"
class="com.google.android.gms.maps.SupportMapFragment"
/>
<ToggleButton
android:id="#+id/tbMode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/map"
android:layout_toRightOf="#+id/btnDirection"
android:textOff="Walking"
android:textOn="Driving" />
<Button
android:id="#+id/btnDirection"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/map"
android:layout_alignTop="#+id/map"
android:layout_marginLeft="62dp"
android:text="#string/getdirection" />
</RelativeLayout>
Finally, i add some code to AndroidManifest as shown bellow :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tugas.akhir"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- Requaired Permissions for Google Maps V2 - Start - Kaplandroid -->
<permission
android:name="com.tugas.akhir.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<!-- External storage for caching. -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="com.tugas.akhir.permission.MAPS_RECEIVE" />
<!-- Maps API needs OpenGL ES 2.0. -->
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<!-- Requaired Permissions for Google Maps V2 - End - Kaplandroid -->
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<!-- API KEY for Google Maps V2 - Start - Kaplandroid -->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="-------- MY GOOGLE API KEY -------------" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<!-- API KEY for Google Maps V2 - End - Kaplandroid -->
<activity
android:name="com.tugas.akhir.MapActivity"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
Later i export it to .apk file, then install it to my device. But,... when i open it, it didnt show any maps, it only show plus & minus button, there is nothing except those button. I've search to internet, it said that my problem is put this code to my AndroidManifest :
<uses-permission android:name="android.permission.INTERNET" />
I've put that code, but it still doesnt show any maps, the some article said that the problem is reference to google play library. I've successfull reference my project to google-play-service library, but it's still failed. Anyone can help to fix my problem, please ??? thank you very much
It looks like your sha1 hash of your certificates or packageId you use is incorrectly set up in google api console for your maps. It's important to use proper sha1 hash and right package id. Also note you may also want to add your debug certificate as well.
It may problem with your API key mentioned in your Android Manifest file. Make sure that it was generated with correct SHA-1 key + your package name mentioned in the android manifest file..
And also check whether Google Maps Android API V2 is turned on in Google APIs Console located in services tab.
Note: After generating new API key uninstall your old app in the device and try again with new installation.
You must change APIKEY value with your own APIKEY as mentioned on Manifest file
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="-------- MY GOOGLE API KEY -------------" />