I'm developing a nearby places app.
No error in code in normal way, but when I run the project, logcat shows this error.
I've googled a lot but nothing solved my problem.
logcat :
07-26 11:21:44.056: E/AndroidRuntime(1924): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=market://details?id=com.google.android.gms flg=0x80000 pkg=com.android.vending }
MainActivity.java
package in.wptrafficanalyzer.locationnearby;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import org.json.JSONObject;
import android.app.Dialog;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends FragmentActivity implements LocationListener{
GoogleMap mGoogleMap;
Spinner mSprPlaceType;
String[] mPlaceType=null;
String[] mPlaceTypeName=null;
double mLatitude=0;
double mLongitude=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Array of place types
mPlaceType = getResources().getStringArray(R.array.place_type);
// Array of place type names
mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);
// Creating an array adapter with an array of Place types
// to populate the spinner
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);
// Getting reference to the Spinner
mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);
// Setting adapter on Spinner to set place types
mSprPlaceType.setAdapter(adapter);
Button btnFind;
// Getting reference to Find Button
btnFind = ( Button ) findViewById(R.id.btn_find);
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();
}else { // Google Play Services are available
// Getting reference to the SupportMapFragment
SupportMapFragment fragment = ( SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
// Getting Google Map
mGoogleMap = fragment.getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location From GPS
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
// Setting click event lister for the find button
btnFind.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int selectedPosition = mSprPlaceType.getSelectedItemPosition();
String type = mPlaceType[selectedPosition];
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location="+mLatitude+","+mLongitude);
sb.append("&radius=5000");
sb.append("&types="+type);
sb.append("&sensor=true");
sb.append("&key=9C:6F:F6:C2:68:9F:EF:26:42:3F:6E:1F:79:8C:18:B3:0E:16:11:A9");
// Creating a new non-ui thread task to download Google place json data
PlacesTask placesTask = new PlacesTask();
// Invokes the "doInBackground()" method of the class PlaceTask
placesTask.execute(sb.toString());
}
});
}
}
/** 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;
}
/** A class, to download Google Places */
private class PlacesTask extends AsyncTask<String, Integer, String>{
String data = null;
// Invoked by execute() method of this object
#Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String result){
ParserTask parserTask = new ParserTask();
// Start parsing the Google places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String,String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
try{
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a List construct */
places = placeJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String,String>> list){
// Clears all the existing markers
mGoogleMap.clear();
for(int i=0;i<list.size();i++){
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, String> hmPlace = list.get(i);
// Getting latitude of the place
double lat = Double.parseDouble(hmPlace.get("lat"));
// Getting longitude of the place
double lng = Double.parseDouble(hmPlace.get("lng"));
// Getting name
String name = hmPlace.get("place_name");
// Getting vicinity
String vicinity = hmPlace.get("vicinity");
LatLng latLng = new LatLng(lat, lng);
// Setting the position for the marker
markerOptions.position(latLng);
// Setting the title for the marker.
//This will be displayed on taping the marker
markerOptions.title(name + " : " + vicinity);
// Placing a marker on the touched position
mGoogleMap.addMarker(markerOptions);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
LatLng latLng = new LatLng(mLatitude, mLongitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
#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
}
}
manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="in.wptrafficanalyzer.locationnearby"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<permission
android:name="in.wptrafficanalyzer.locationnearby.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="in.wptrafficanalyzer.locationnearby.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-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="in.wptrafficanalyzer.locationnearby.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="9C:6F:F6:C2:68:9F:EF:26:42:3F:6E:1F:79:8C:18:B3:0E:16:11:A9"/>
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version" />
</application>
</manifest>
Please give me your best help.
Thanks in advance
Your device doesn't have play store to handle the market protocol "market://details?id=com.google.android.gms" you need to install play services on that device or run your code on another device that has play services
Edit
this is how you check for play services
int supported = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if(supported == 0) // success! do something
Log.v("play services ", " supported");
else
Log.v("play services ", " not supported");
Have you defined it in your manifest.xml, like so
<activity
android:name=".ActivityName"
android:label="#string/label" >
</activity>
Related
I'm developing an app which can read data from a Bluetooth RFID Reader, but everytime i start the BluetoothActivity (it's a tabbed activity), it always shows a ClassCastException, below is my code..
BluetoothActivity class:
package com.siscaproject.sisca.Activity;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.siscaproject.sisca.Fragment.RegisterFragment;
import com.siscaproject.sisca.Fragment.SearchFragment;
import com.siscaproject.sisca.R;
import com.siscaproject.sisca.Utilities.FamsModel;
import com.siscaproject.sisca.Utilities.TSLBluetoothDeviceActivity;
import com.siscaproject.sisca.Utilities.TSLBluetoothDeviceApplication;
import com.uk.tsl.rfid.asciiprotocol.AsciiCommander;
import com.uk.tsl.rfid.asciiprotocol.responders.LoggerResponder;
import java.util.ArrayList;
import butterknife.BindView;
import butterknife.ButterKnife;
public class BluetoothActivity extends TSLBluetoothDeviceActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
#BindView(R.id.viewpager_bluetooth) ViewPager mViewPager;
#BindView(R.id.toolbar_bluetooth) Toolbar mToolbar;
#BindView(R.id.tab_bluetooth) TabLayout mTabLayout;
private FamsModel mModel;
public AsciiCommander getCommander(){
return ((TSLBluetoothDeviceApplication) getApplication()).getCommander();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
ButterKnife.bind(this);
setSupportActionBar(mToolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
setupViewPager(mViewPager);
mTabLayout.setupWithViewPager(mViewPager);
AsciiCommander commander = getCommander();
// Add the LoggerResponder - this simply echoes all lines received from the reader to the log
// and passes the line onto the next responder
// This is added first so that no other responder can consume received lines before they are logged.
commander.addResponder(new LoggerResponder());
// Add a synchronous responder to handle synchronous commands
commander.addSynchronousResponder();
}
private void setupViewPager(ViewPager viewPager){
SectionsPagerAdapter adapter = new SectionsPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new RegisterFragment(), "REGISTER");
adapter.addFragment(new SearchFragment(), "SEARCH");
viewPager.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_bluetooth, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.menu_item_reconnect_reader) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_bluetooth, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> fragmentList = new ArrayList<>();
private ArrayList<String> fragmentTitleList = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
// Show 3 total pages.
return fragmentList.size();
}
public void addFragment(Fragment fragment, String title ){
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
}
}
TSLBluetoothDeviceActivity class:
package com.siscaproject.sisca.Utilities;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import com.siscaproject.sisca.BuildConfig;
import com.uk.tsl.rfid.DeviceListActivity;
import com.uk.tsl.rfid.asciiprotocol.AsciiCommander;
import java.util.Timer;
import java.util.TimerTask;
public class TSLBluetoothDeviceActivity extends AppCompatActivity {
// Debugging
private static final String TAG = "TSLBTDeviceActivity";
private static final boolean D = BuildConfig.DEBUG;
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
private static final int REQUEST_ENABLE_BT = 3;
// Local Bluetooth adapter
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothDevice mDevice = null;
protected AsciiCommander getCommander() {
return ((TSLBluetoothDeviceApplication) getApplication()).getCommander();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// Create the AsciiCommander to talk to the reader (if it doesn't already exist)
if (getCommander() == null) {
try {
TSLBluetoothDeviceApplication app = (TSLBluetoothDeviceApplication) getApplication();
AsciiCommander commander = new AsciiCommander(getApplicationContext());
app.setCommander(commander);
} catch (Exception e) {
fatalError("Unable to create AsciiCommander!");
}
}
}
// Terminate the app with the given message
private void fatalError(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
finish();
}
}, 1800);
}
protected void bluetoothNotAvailableError(String message) {
fatalError(message);
}
#Override
public void onStart() {
super.onStart();
// If no other attempt to connect is ongoing try to connect to last used reader
// Note: When returning from the Device List activity
if (mBluetoothAdapter.isEnabled()) {
if (mDevice == null) {
// Attempt to reconnect to the last reader used
Toast.makeText(this, "Reconnecting to last used reader...", Toast.LENGTH_SHORT).show();
getCommander().connect(null);
}
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
#Override
public void onStop() {
super.onStop();
getCommander().disconnect();
mDevice = null;
}
protected void connectToDevice(Intent deviceData, boolean secure) {
Toast.makeText(this.getApplicationContext(), "Connecting...", Toast.LENGTH_LONG).show();
// Get the device MAC address
String address = deviceData.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BluetoothDevice object
mDevice = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
if (mDevice != null) {
getCommander().connect(mDevice);
} else {
if (D) Log.e(TAG, "Unable to obtain BluetoothDevice!");
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (D)
Log.d(TAG, "selectDevice() onActivityResult: " + resultCode + " for request: " + requestCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectToDevice(data, true);
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectToDevice(data, false);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode != Activity.RESULT_OK) {
// User did not enable Bluetooth or an error occurred
Log.d(TAG, "BT not enabled");
bluetoothNotAvailableError("Bluetooth was not enabled\nApplication Quitting...");
}
}
}
public void selectDevice() {
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
}
public void disconnectDevice() {
mDevice = null;
getCommander().disconnect();
}
public void reconnectDevice() {
getCommander().connect(null);
}
}
The error log:
11-21 14:47:54.836 18956-18956/com.siscaproject.sisca E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.siscaproject.sisca, PID: 18956
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.siscaproject.sisca/com.siscaproject.sisca.Activity.BluetoothActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to com.siscaproject.sisca.Utilities.TSLBluetoothDeviceApplication
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2318)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to com.siscaproject.sisca.Utilities.TSLBluetoothDeviceApplication
at com.siscaproject.sisca.Activity.BluetoothActivity.getCommander(BluetoothActivity.java:51)
at com.siscaproject.sisca.Utilities.TSLBluetoothDeviceActivity.onCreate(TSLBluetoothDeviceActivity.java:45)
at com.siscaproject.sisca.Activity.BluetoothActivity.onCreate(BluetoothActivity.java:57)
at android.app.Activity.performCreate(Activity.java:5411)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2396)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
at dalvik.system.NativeStart.main(Native Method)
I've followed this code from an app that works fine, but when I implemented it in my project it always shows this error, I'm not sure what I'm doing wrong.
---EDIT---
TSLBluetoothDeviceApplication class:
package com.siscaproject.sisca.Utilities;
import android.app.Application;
import com.uk.tsl.rfid.asciiprotocol.AsciiCommander;
public class TSLBluetoothDeviceApplication extends Application {
private static AsciiCommander commander = null;
/// Returns the current AsciiCommander
public AsciiCommander getCommander() {
return commander;
}
/// Sets the current AsciiCommander
public void setCommander(AsciiCommander _commander) {
commander = _commander;
}
}
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.siscaproject.sisca">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:replace="android:icon">
<activity
android:name=".Activity.LoginActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Activity.BluetoothTestActivity"
android:theme="#style/StandardTheme" />
<activity
android:name=".Activity.HomeActivity"
android:label="#string/title_activity_home"
android:theme="#style/AppTheme" />
<meta-data
android:name="com.google.android.gms.vision.DEPENDENCIES"
android:value="barcode" />
<activity android:name=".Activity.QRActivity" />
<activity
android:name=".Activity.BluetoothActivity"
android:label="#string/title_activity_bluetooth"
android:theme="#style/AppTheme"></activity>
</application>
</manifest>
getApplication() inside an activity returns an object of type Application. In your case you are trying to cast this object into TSLBluetoothDeviceApplication which, as defined by you, is an Activity type class.
As I see, you are trying to call getCommander() which is defined already in your TSL activity class. I assume you want getCommander() method from another class.. Make sure which one is.
public AsciiCommander getCommander(){
return ((TSLBluetoothDeviceApplication) getApplication()).getCommander();
}
This method is already inside TSLBluetoothDeviceApplication class.. I don't know what are you trying to achieve by trying to call same method which is already in your current class.
EDIT:
After the edited post, we noticed that the class was properly implemented, just forgot to add
android:name="com.path.to.ApplicationClass" into the Manifestfile under <application/> tag.
I will let the above answer also, because it may help others
Happy coding <3
It's clear that your application class is not used. You need to add it to your xml Application tag like this:
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:name="com.siscaproject.sisca.Utilities. TSLBluetoothDeviceApplication"
android:theme="#style/AppTheme"
tools:replace="android:icon">
and the only change is adding android:name="com.siscaproject.sisca.Utilities. TSLBluetoothDeviceApplication" to the Application tag as your customized class.
I am currently developing my first app that able to switch activity tab (Android's Fragment). I have 4 tabs, in one of the tabs, I have implemented an image recognition for character recognition (OCR). I used simplified OCR Tesseract library which is called Easy OCR Library made by Priyank Verma. I have tested the example from that library and it works. But when I use the library for my own app, it doesn't work properly.
Let me explain, in one of my app's tab, I have a 'Scan' button that utilizes use my phone camera to take a picture. After the picture have been taken, my app should scan the captured image in the saved directory for character recognition. Next, my app will return to the previous 'Scan' tab and then will display the output of the character recognition above the 'Scan' button in that tab. And that just it, my app doesn't seem to scan. The real problem is that after the picture have been taken & saved, my app returns back to the tab with no output at all. My code should work but sadly it doesn't. No error, no nothing and I am losing my mind for days to figure out what is wrong.
Here's the code:-
---------- My App's Manifest ----------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kaydarinapp.queueappv2">
<!-- Save file permission -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<!-- Read file permission -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!-- Camera permission -->
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<!-- Internet permission -->
<uses-permission android:name="android.permission.INTERNET" />
<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"
android:configChanges="keyboardHidden|orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
---------- From My App's Tab ----------
My Tab's XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".Tab2"
android:gravity="center_horizontal"
>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:layout_marginTop="45dp"
android:layout_gravity="center_horizontal"
android:textSize="8pt"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:layout_marginTop="20dp"
android:text="Scan"
android:layout_gravity="center_vertical" />
</LinearLayout>
My Tab Java
package com.kaydarinapp.queueappv2;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.wordpress.priyankvex.easyocrscannerdemo.Config;
import com.wordpress.priyankvex.easyocrscannerdemo.EasyOcrScanner;
import com.wordpress.priyankvex.easyocrscannerdemo.EasyOcrScannerListener;
/**
* Created by Kaydarin on 6/1/2016.
*/
//Our class extending fragment
public class Tab2 extends Fragment implements EasyOcrScannerListener {
private LinearLayout linearLayout;
private FragmentActivity fragActivity;
EasyOcrScanner mEasyOcrScanner;
TextView textView;
ProgressDialog mProgressDialog;
Button btnCapture;
//Overriden method onCreateView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
fragActivity = super.getActivity();
linearLayout = (LinearLayout) inflater.inflate(R.layout.tab2, container, false);
textView = (TextView) fragActivity.findViewById(R.id.textView);
// initialize EasyOcrScanner instance.
mEasyOcrScanner = new EasyOcrScanner(getActivity(), "EasyOcrScanner",
Config.REQUEST_CODE_CAPTURE_IMAGE, "eng");
// Set ocrScannerListener
mEasyOcrScanner.setOcrScannerListener(this);
btnCapture = (Button) linearLayout.findViewById(R.id.button);
btnCapture.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
mEasyOcrScanner.takePicture();
}
});
return linearLayout;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Call onImageTaken() in onActivityResult.
if (resultCode == getActivity().RESULT_OK && requestCode == Config.REQUEST_CODE_CAPTURE_IMAGE){
mEasyOcrScanner.onImageTaken();
}
}
/**
* Callback when after taking picture, scanning process starts.
* Good place to show a progress dialog.
* #param filePath file path of the image file being processed.
*/
#Override
public void onOcrScanStarted(String filePath) {
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setMessage("Scanning...");
mProgressDialog.show();
}
/**
* Callback when scanning is finished.
* Good place to hide teh progress dialog.
* #param bitmap Bitmap of image that was scanned.
* #param recognizedText Scanned text.
*/
#Override
public void onOcrScanFinished(Bitmap bitmap, String recognizedText) {
textView.setText(recognizedText);
if (mProgressDialog.isShowing()){
mProgressDialog.dismiss();
}
}
}
---------- From Easy OCR Library ----------
Easy OCR Library's Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.wordpress.priyankvex.easyocrscanner">
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA"/>
</manifest>
Config Java
package com.wordpress.priyankvex.easyocrscannerdemo;
/**
* Created by Priyank(#priyankvex) on 27/8/15.
*/
public class Config {
public static String TAG = "OcrScanner";
public static int REQUEST_CODE_CAPTURE_IMAGE = 1995;
}
EasyOCRScannerListener Java
package com.wordpress.priyankvex.easyocrscannerdemo;
import android.graphics.Bitmap;
/**
* Created by Priyank(#priyankvex) on 27/8/15.
*
* Interface for the callbacks for {#link EasyOcrScanner}.
*/
public interface EasyOcrScannerListener {
public void onOcrScanStarted(String filePath);
public void onOcrScanFinished(Bitmap bitmap, String recognizedText);
}
EasyOCRScanner Java
package com.wordpress.priyankvex.easyocrscannerdemo;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import java.io.File;
import java.util.Calendar;
/**
* Created by Priyank(#priyankvex) on 27/8/15.
*
* Class to handle scanning of image.
*/
public class EasyOcrScanner {
protected Activity mActivity;
private String directoryPathOriginal;
private String filePathOriginal;
private int requestCode;
private EasyOcrScannerListener mOcrScannerListener;
private String trainedDataCode;
public EasyOcrScanner(Activity activity, String directoryPath, int requestCode, String trainedDataCode){
this.mActivity = activity;
this.directoryPathOriginal = directoryPath;
this.requestCode = requestCode;
this.trainedDataCode = trainedDataCode;
}
public void takePicture(){
Intent e = new Intent("android.media.action.IMAGE_CAPTURE");
this.filePathOriginal = FileUtils.getDirectory(this.directoryPathOriginal) + File.separator + Calendar.getInstance().getTimeInMillis() + ".jpg";
e.putExtra("output", Uri.fromFile(new File(this.filePathOriginal)));
startActivity(e);
}
public void onImageTaken(){
Log.d(Config.TAG, "onImageTaken with path " + this.filePathOriginal);
ImageProcessingThread thread = new ImageProcessingThread(this.mOcrScannerListener,
this.filePathOriginal, this.directoryPathOriginal, this.mActivity, this.trainedDataCode);
thread.execute();
}
private void startActivity(Intent intent){
if(this.mActivity != null) {
this.mActivity.startActivityForResult(intent, this.requestCode);
}
}
public void setOcrScannerListener(EasyOcrScannerListener mOcrScannerListener) {
this.mOcrScannerListener = mOcrScannerListener;
}
}
FileUtils Java
package com.wordpress.priyankvex.easyocrscannerdemo;
import android.os.Environment;
import android.util.Log;
import java.io.File;
/**
* Created by Priyank(#priyankvex) on 27/8/15.
*/
public class FileUtils {
public static String getDirectory(String folderName) {
File directory = null;
directory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + folderName);
if(!directory.exists()) {
directory.mkdirs();
}
return directory.getAbsolutePath();
}
public static String getTessdataDirectory(String directoryPath){
File tessdataDirectory = new File(directoryPath + "/tessdata");
if (tessdataDirectory.mkdirs()){
Log.d(Config.TAG, "tessdata directory created");
}
return tessdataDirectory.getAbsolutePath();
}
}
ImageProcessingThread Java
package com.wordpress.priyankvex.easyocrscannerdemo;
import android.app.Activity;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.AsyncTask;
import android.util.Log;
import com.googlecode.tesseract.android.TessBaseAPI;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by Priyank(#priyankvex) on 27/8/15.
*
* Async Task to process the image and scan the image using tesseract library.
* Equipped with proper callbacks.
*/
public class ImageProcessingThread extends AsyncTask<Void, Void, Void> {
private EasyOcrScannerListener mOcrScannerListener;
private String filePath;
private Bitmap mBitmap;
private String scannedText;
// trained data file used by Tesseract will be copied in directoryPath/tessdata
private String directoryPath;
private String absoluteDirectoryPath;
private Activity mActivity;
String trainedDataCode;
public ImageProcessingThread(EasyOcrScannerListener ocrScannerListener, String filePath,
String directoryPath, Activity activity, String trainedDataCode) {
this.mOcrScannerListener = ocrScannerListener;
this.filePath = filePath;
this.directoryPath = directoryPath;
this.absoluteDirectoryPath = FileUtils.getDirectory(this.directoryPath);
this.mActivity = activity;
this.trainedDataCode = trainedDataCode;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mOcrScannerListener.onOcrScanStarted(this.filePath);
}
#Override
protected Void doInBackground(Void... params) {
processImage();
makeTessdataReady();
scannedText = scanImage();
Log.d(Config.TAG, "Scanned test : " + scannedText);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mOcrScannerListener.onOcrScanFinished(mBitmap, scannedText);
}
private void processImage() {
int imageOrientationCode = getImageOrientation();
Bitmap rawBitmap = getBitmapFromPath();
// Getting the bitmap in right orientation.
this.mBitmap = rotateBitmap(rawBitmap, imageOrientationCode);
}
private Bitmap getBitmapFromPath() {
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(this.filePath, bmOptions);
return bitmap;
}
private int getImageOrientation() {
ExifInterface exif = null;
try {
exif = new ExifInterface(this.filePath);
} catch (IOException e) {
e.printStackTrace();
}
assert exif != null;
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
return orientation;
}
private Bitmap rotateBitmap(Bitmap bitmap, int orientation){
Matrix matrix = new Matrix();
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
return bitmap;
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
matrix.setScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
matrix.setRotate(180);
break;
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
matrix.setRotate(180);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_TRANSPOSE:
matrix.setRotate(90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_90:
matrix.setRotate(90);
break;
case ExifInterface.ORIENTATION_TRANSVERSE:
matrix.setRotate(-90);
matrix.postScale(-1, 1);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
matrix.setRotate(-90);
break;
default:
return bitmap;
}
try {
Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.recycle();
return bmRotated;
}
catch (OutOfMemoryError e) {
e.printStackTrace();
return null;
}
}
private String scanImage(){
TessBaseAPI baseApi = new TessBaseAPI();
Log.d(Config.TAG, "Data path : " + FileUtils.getDirectory(this.directoryPath));
baseApi.init(FileUtils.getDirectory(this.directoryPath) + "/", this.trainedDataCode);
baseApi.setImage(this.mBitmap);
String recognizedText = baseApi.getUTF8Text();
baseApi.end();
return recognizedText;
}
private void makeTessdataReady(){
// created test data directory if necessary under absoluteDirectoryPath and returns its absolute path.
String tessdirectoryPath = FileUtils.getTessdataDirectory(this.absoluteDirectoryPath);
if (!(new File(tessdirectoryPath+ "/" + this.trainedDataCode + ".traineddata")).exists()) {
try {
AssetManager assetManager = mActivity.getAssets();
InputStream in = assetManager.open("tessdata/" + this.trainedDataCode + ".traineddata");
//GZIPInputStream gin = new GZIPInputStream(in);
// Output stream with the location where we have to write the eng.traineddata file.
OutputStream out = new FileOutputStream(tessdirectoryPath + "/" + this.trainedDataCode
+ ".traineddata");
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
//while ((lenf = gin.read(buff)) > 0) {
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
//gin.close();
out.close();
Log.v(Config.TAG, "Copied " + " traineddata");
} catch (IOException e) {
Log.e(Config.TAG, "Was unable to copy " + " traineddata " + e.toString());
}
}
else{
Log.d(Config.TAG, "tessdata already present");
}
}
}
I hope you guys can help me. It's been days to figure out what's wrong with this code.......
I guess the problem is that the camera activity does not return RESULT_OK, but RESULT_CANCELED - therefore tesseract is never called. You can verify this e. g. by adding in "Tab2.java" at the start of method "onActivityResult":
Log.d("PictureEdit", "onActivityResult w/ resultCode=" + resultCode + " (is ok: " + (resultCode == RESULT_OK) + " is canceled: " + (resultCode == RESULT_CANCELED) + ")" + " requestCode=" + requestCode);
Why is that so? Because starting with Android 6 (Marshmallow) it is not suffice to just declare the necessary permissions in the manifest. Additionally the permissions must got at runtime from the user.
See here: https://developer.android.com/training/permissions/requesting.html
Here is the code I use for getting permissions to camera and r/w to external storage:
private void checkPermissions(){
if (Build.VERSION.SDK_INT >= 23) {
boolean needWriteExtStorage = checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED;
boolean needCamera = checkSelfPermission(android.Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED;
if (needWriteExtStorage || needCamera){
String[] permissions = new String[((needWriteExtStorage)?(1):(0)) + ((needCamera)?(1):(0))];
int idx = 0;
if (needWriteExtStorage){
permissions[idx] = android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
idx++;
}
if (needCamera){
permissions[idx] = android.Manifest.permission.CAMERA;
idx++;
}
ActivityCompat.requestPermissions(
this, permissions, 1);
}
} else {
//permission is automatically granted on sdk<23 upon installation
//Log.e("testing", "Permission is already granted");
}
}
I'm having a problem querying a database in Ragic off of Android. I've SUCCESSFULLY created a program in Eclipse that queries the online database and downloads all the JSONS, turns them into Objects, and then puts them into an ArrayList. Unfortunately, I'm running into a problem trying to download the same data using the exactly same code in Android. I've already added the permission for the internet (as shown in the AndroidManifest.xml). The code compiles and all, but throws the NullPointerException("RUNTIME EXCEPTION/ALLDOWNLOADEXCEPTIONS") at the end of the MapsActivity.java file. That is the problem, but I don't know what it causing it. Please help with that.
Here is the MapsActivity.java:
package com.main.parcaretestversion;
import android.graphics.Color;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import java.io.*;
import java.net.*;
import java.util.*;
import com.google.android.gms.maps.model.Polygon;
import com.google.android.gms.maps.model.PolygonOptions;
import com.google.gson.*;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
ArrayList<ParkingSpot> list = init();
System.exit(0);
for (ParkingSpot spot: list) {
PolygonOptions rectOptions = new PolygonOptions()
.addAll(spot.getArrayListLatLngDefault());
if (spot.getStatus()) {
rectOptions.fillColor(Color.GREEN);
} else {
rectOptions.fillColor(Color.RED);
}
Polygon polygon = mMap.addPolygon(rectOptions);
}
}
public ArrayList<ParkingSpot> format(String input) {
ArrayList<ParkingSpot> list = new ArrayList<ParkingSpot>();
JsonElement root = new JsonParser().parse(input);
for (int i = 0; i <= 9; i++) {
String uid = root.getAsJsonObject().get(String.valueOf(i) + "").getAsJsonObject().get("ID").getAsString();
String coordinate1 = root.getAsJsonObject().get(String.valueOf(i) + "").getAsJsonObject().get("Coordinate 1").getAsString();
String coordinate2 = root.getAsJsonObject().get(String.valueOf(i) + "").getAsJsonObject().get("Coordinate 2").getAsString();
String coordinate3 = root.getAsJsonObject().get(String.valueOf(i) + "").getAsJsonObject().get("Coordinate 3").getAsString();
String coordinate4 = root.getAsJsonObject().get(String.valueOf(i) + "").getAsJsonObject().get("Coordinate 4").getAsString();
String statusTemp = root.getAsJsonObject().get(String.valueOf(i) + "").getAsJsonObject().get("Status").getAsString();
boolean status;
if (statusTemp.equals("true")) {
status = true;
} else {
status = false;
}
list.add(new ParkingSpot(uid, status, new LatLong(coordinate1), new LatLong(coordinate2), new LatLong(coordinate3), new LatLong(coordinate4)));
}
return list;
}
public ArrayList<ParkingSpot> init() {
String apiKey = "some api key";
try {
//
URL url = new URL("https://api.ragic.com/some username/some sheet/1");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setRequestProperty("Authorization", "Basic " + apiKey);
InputStream content = (InputStream) connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String uglyJson = "";
for (String line; (line = reader.readLine()) != null; ) {
uglyJson += line;
}
ArrayList<ParkingSpot> list = format(uglyJson);
throw new NullPointerException(uglyJson);
//return list;
} catch (MalformedURLException e) {
throw new NullPointerException("MALFORUMED URL EXCEPTION");
} catch (RuntimeException allDownloadExceptions) {
throw new NullPointerException("RUNTIME EXCEPTION/ALLDOWNLOADEXCEPTIONS");
} catch (ProtocolException e) {
throw new NullPointerException("PROTOCOL EXCEPTION");
} catch (IOException e) {
throw new NullPointerException("IO EXCEPTION");
}
}
}
Here is the AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Use asyncTasks in your mainActivity.
For example.
private class LongOperation extends AsyncTask<String, Void, ArrayList> {
#Override
protected ArrayList doInBackground(String... params) {
URL url = new URL("https://api.ragic.com/some username/some sheet/1");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setRequestProperty("Authorization", "Basic " + apiKey);
InputStream content = (InputStream) connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String uglyJson = "";
for (String line; (line = reader.readLine()) != null; ) {
uglyJson += line;
}
ArrayList<ParkingSpot> list = format(uglyJson);
throw new NullPointerException(uglyJson);
return list;
}
#Override
protected void onPostExecute(ArrayList result) {
//Handle result here.
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
now make call for this call
new LongOperation().execute();
Hope it will help
I've been going at this for a while. I've searched and tried everything I've seen. I cannot get this damn activity to event be declared. I have a MarkerActivity for creating markers on my map. When clicked, I want them to open an activity and pass a variable. I've tried everything and keep crashing with a NullPointerException. Code below:
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tapmap.app.tapmapapp" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<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" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" /><meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyAksheZLMAALUfLHKWOsfTFCz7iP_KwpCE" />
<activity
android:name=".MapsActivity"
android:label="#string/title_activity_maps" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".BarBrewry"
android:configChanges="orientation|keyboardHidden|screenSize"
android:label="#string/title_activity_bar_brewry"
android:theme="#style/FullscreenTheme" >
</activity>
<activity
android:name=".MarkerActivity"
android:label="#string/title_activity_marker">
</activity>
</application>
</manifest>
Marker.java:
package com.tapmap.app.tapmapapp;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
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.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.common.api.GoogleApiClient;
public class MarkerActivity extends android.support.v4.app.FragmentActivity implements GoogleMap.OnMarkerClickListener {
public Marker myMarker;
public LatLng latLng;
public String venueid;
public String venuename;
public String[] taps;
public String address;
public Integer markid;
public void setUpMap() {
MapsActivity.mMap.setOnMarkerClickListener(this);
//googleMap.setOnInfoWindowClickListener(listener);
myMarker = MapsActivity.mMap.addMarker(new MarkerOptions()
.position(latLng)
.title(venuename)
.snippet("Check Taps/Get Directions")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.tmico))
);
}
#Override
public boolean onMarkerClick(final Marker marker) {
Log.i("RetrieveFeedTask", MarkerActivity.this + "Marker Clicked" + MapsActivity.venues.get(markid).venuename);
try {
Intent bar = new Intent(MarkerActivity.this, BarBrewry.class);
// bar.putExtra("venuename", venuename);
//this.startActivity(bar);
} catch(Exception vo) {
Log.i("RetrieveFeedTask", "Error opening: " + vo.getMessage());
}
return true;
}
}
Stack trace:
9153-9153/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:135)
at android.content.ComponentName.<init>(ComponentName.java:75)
at android.content.Intent.<init>(Intent.java:3662)
at com.tapmap.app.tapmapapp.MarkerActivity.onMarkerClick(MarkerActivity.java:50)
at com.google.android.gms.maps.GoogleMap$10.zza(Unknown Source)
at com.google.android.gms.maps.internal.zzn$zza.onTransact(Unknown Source)
at android.os.Binder.transact(Binder.java:347)
at com.google.android.gms.maps.internal.bd.a(SourceFile:84)
at com.google.maps.api.android.lib6.d.as.b(Unknown Source)
at com.google.maps.api.android.lib6.gmm6.c.e.a(Unknown Source)
at com.google.maps.api.android.lib6.gmm6.n.av.a(Unknown Source)
at com.google.maps.api.android.lib6.gmm6.n.be.a(Unknown Source)
at com.google.maps.api.android.lib6.gmm6.n.bd.a(Unknown Source)
at com.google.maps.api.android.lib6.gmm6.n.bt.d(Unknown Source)
at com.google.maps.api.android.lib6.gmm6.n.ak.onSingleTapConfirmed(Unknown Source)
at com.google.maps.api.android.lib6.gmm6.h.g.onSingleTapConfirmed(Unknown Source)
at com.google.maps.api.android.lib6.gmm6.h.i.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
MapsActivity
package com.tapmap.app.tapmapapp;
import android.content.IntentSender;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
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.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.common.api.GoogleApiClient;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MapsActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
public static GoogleMap mMap; // Might be null if Google Play services APK is not available.
private GoogleApiClient mGoogleApiClient;
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
public static final String TAG = MapsActivity.class.getSimpleName();
public static List<MarkerActivity> venues = new ArrayList<MarkerActivity>();
private LocationRequest mLocationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {#link #setUpMap()} once when {#link #mMap} is not null.
* <p/>
* If it isn't installed {#link SupportMapFragment} (and
* {#link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
* install/update the Google Play services APK on their device.
* <p/>
* A user can return to this FragmentActivity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the FragmentActivity may not
* have been completely destroyed during this process (it is likely that it would only be
* stopped or paused), {#link #onCreate(Bundle)} may not be called again so we should call this
* method in {#link #onResume()} to guarantee that it will be called.
*/
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) {
try {
setUpMap();
} catch(IOException ioe){
//nothing
}
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p/>
* This should only be called once and when we are sure that {#link #mMap} is not null.
*/
private void setUpMap()throws IOException {
mMap.setMyLocationEnabled(true);
Log.i("MapsActivity","calling get locs");
try {
Log.i("RetrieveFeedTask", "Starting Call");
new RetrieveFeedTask().execute("http://fltapmap.com/get-locs.php");
} catch (Exception alle) {
Log.i("RetrieveFeedTask", "Error" + alle.getMessage());
}
}
#Override
public void onConnected(Bundle bundle) {
Log.i(TAG, "Location services connected.");
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
else {
handleNewLocation(location);
}
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
CameraUpdate zoom=CameraUpdateFactory.zoomTo(10);
mMap.animateCamera(zoom);
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Location services suspended. Please reconnect.");
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
#Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
}
BarBrewry is bar barebones right now just for testing
package com.tapmap.app.tapmapapp;
import com.tapmap.app.tapmapapp.util.SystemUiHider;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
public class BarBrewry extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
}
Perhaps you need to implement the public void onCreate(Bundle savedInstanceState) method..
It is because you use a wrong context in that line:
Intent bar = new Intent(MarkerActivity.this, BarBrewry.class);
bar.putExtra("venuename", venuename);
this.startActivity(bar);
this is not a valid context in an inner class there. Try to use:
MarkerActivity.this.startActivity(bar);
Additionally you have to implement onCreate in your MarkerActivity, otherwise there would never exist an instance of this activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
}
I don't exactly know what you want to achieve with MarkerActivity but like Daniel Nugent mentioned in the comments, you should consider merging your MarkerActivity with MapsActivity.
I'm trying to make an app in Android Studio which requires you to download a file to the sdcard/Download/ folder on the users device. The problem is that when I enter the URL to download from and click Download, the app says "Unfortunately, * has stopped". I have quite a few files so here they are.
First, heres the Manifest...
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.NautGames.xecta.app" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.NautGames.xecta.app.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>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<!-- Permission: Writing to SDCard -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
</manifest>
Heres the MainActivity class...
package com.NautGames.xecta.app;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
//Chat bot library
import org.alicebot.ab.Chat;
import org.alicebot.ab.Bot;
import android.view.View;
import android.widget.Button;
import android.os.Environment;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
TextView input;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//EditText mEdit = (EditText)findViewById(R.id.editText1);
public void buttonOnClick(View v)
{
input = (TextView) findViewById(R.id.editText1);
String dbPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/Ab";
Button button=(Button) v;
//Creating bot
String botname="xecta";
String path= dbPath;
Bot xecta = new Bot(botname, path);
Chat chatSession = new Chat(xecta);
String request = input.getText().toString();
String response = chatSession.multisentenceRespond(request);
((Button) v).setText(response);
}
public void buttonDownload(View v)
{
}
#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 boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
DownloaderThread (to download file)...
package com.NautGames.xecta.app;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.os.Environment;
import android.os.Message;
/**
* Downloads a file in a thread. Will send messages to the
* AndroidFileDownloader activity to update the progress bar.
*/
public class DownloaderThread extends Thread
{
// constants
private static final int DOWNLOAD_BUFFER_SIZE = 4096;
// instance variables
private AndroidFileDownloader parentActivity;
private String downloadUrl;
/**
//Instantiates a new DownloaderThread object.
// #param parentActivity Reference to AndroidFileDownloader activity.
// #param inUrl String representing the URL of the file to be downloaded.
*/
public DownloaderThread(AndroidFileDownloader inParentActivity, String inUrl)
{
downloadUrl = "";
if(inUrl != null)
{
downloadUrl = inUrl;
}
parentActivity = inParentActivity;
}
/**
* Connects to the URL of the file, begins the download, and notifies the
* AndroidFileDownloader activity of changes in state. Writes the file to
* the root of the SD card.
*/
#Override
public void run()
{
URL url;
URLConnection conn;
int fileSize, lastSlash;
String fileName;
BufferedInputStream inStream;
BufferedOutputStream outStream;
File outFile;
FileOutputStream fileStream;
Message msg;
// we're going to connect now
msg = Message.obtain(parentActivity.activityHandler,
AndroidFileDownloader.MESSAGE_CONNECTING_STARTED,
0, 0, downloadUrl);
parentActivity.activityHandler.sendMessage(msg);
try
{
url = new URL(downloadUrl);
conn = url.openConnection();
conn.setUseCaches(false);
fileSize = conn.getContentLength();
// get the filename
lastSlash = url.toString().lastIndexOf('/');
fileName = "file.bin";
if(lastSlash >=0)
{
fileName = url.toString().substring(lastSlash + 1);
}
if(fileName.equals(""))
{
fileName = "file.bin";
}
// notify download start
int fileSizeInKB = fileSize / 1024;
msg = Message.obtain(parentActivity.activityHandler,
AndroidFileDownloader.MESSAGE_DOWNLOAD_STARTED,
fileSizeInKB, 0, fileName);
parentActivity.activityHandler.sendMessage(msg);
// start download
inStream = new BufferedInputStream(conn.getInputStream());
outFile = new File(Environment.getExternalStorageDirectory() + "/" + fileName);
fileStream = new FileOutputStream(outFile);
outStream = new BufferedOutputStream(fileStream, DOWNLOAD_BUFFER_SIZE);
byte[] data = new byte[DOWNLOAD_BUFFER_SIZE];
int bytesRead = 0, totalRead = 0;
while(!isInterrupted() && (bytesRead = inStream.read(data, 0, data.length)) >= 0)
{
outStream.write(data, 0, bytesRead);
// update progress bar
totalRead += bytesRead;
int totalReadInKB = totalRead / 1024;
msg = Message.obtain(parentActivity.activityHandler,
AndroidFileDownloader.MESSAGE_UPDATE_PROGRESS_BAR,
totalReadInKB, 0);
parentActivity.activityHandler.sendMessage(msg);
}
outStream.close();
fileStream.close();
inStream.close();
if(isInterrupted())
{
// the download was canceled, so let's delete the partially downloaded file
outFile.delete();
}
else
{
// notify completion
msg = Message.obtain(parentActivity.activityHandler,
AndroidFileDownloader.MESSAGE_DOWNLOAD_COMPLETE);
parentActivity.activityHandler.sendMessage(msg);
}
}
catch(MalformedURLException e)
{
String errMsg = parentActivity.getString(R.string.error_message_bad_url);
msg = Message.obtain(parentActivity.activityHandler,
AndroidFileDownloader.MESSAGE_ENCOUNTERED_ERROR,
0, 0, errMsg);
parentActivity.activityHandler.sendMessage(msg);
}
catch(FileNotFoundException e)
{
String errMsg = parentActivity.getString(R.string.error_message_file_not_found);
msg = Message.obtain(parentActivity.activityHandler,
AndroidFileDownloader.MESSAGE_ENCOUNTERED_ERROR,
0, 0, errMsg);
parentActivity.activityHandler.sendMessage(msg);
}
catch(Exception e)
{
String errMsg = parentActivity.getString(R.string.error_message_general);
msg = Message.obtain(parentActivity.activityHandler,
AndroidFileDownloader.MESSAGE_ENCOUNTERED_ERROR,
0, 0, errMsg);
parentActivity.activityHandler.sendMessage(msg);
}
}
}
And lastly, The AndroidFileDownload(also to download file)...
package com.NautGames.xecta.app;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AndroidFileDownloader extends Activity implements OnClickListener
{
// Used to communicate state changes in the DownloaderThread
public static final int MESSAGE_DOWNLOAD_STARTED = 1000;
public static final int MESSAGE_DOWNLOAD_COMPLETE = 1001;
public static final int MESSAGE_UPDATE_PROGRESS_BAR = 1002;
public static final int MESSAGE_DOWNLOAD_CANCELED = 1003;
public static final int MESSAGE_CONNECTING_STARTED = 1004;
public static final int MESSAGE_ENCOUNTERED_ERROR = 1005;
// instance variables
private AndroidFileDownloader thisActivity;
private Thread downloaderThread;
private ProgressDialog progressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
thisActivity = this;
downloaderThread = null;
progressDialog = null;
setContentView(R.layout.activity_main);
Button button = (Button) this.findViewById(R.id.download_button);
button.setOnClickListener(this);
}
/** Called when the user clicks on something. */
#Override
public void onClick(View view)
{
EditText urlInputField = (EditText) this.findViewById(R.id.url_input);
String urlInput = urlInputField.getText().toString();
downloaderThread = new DownloaderThread(thisActivity, urlInput);
downloaderThread.start();
}
/**
* This is the Handler for this activity. It will receive messages from the
* DownloaderThread and make the necessary updates to the UI.
*/
public Handler activityHandler = new Handler()
{
public void handleMessage(Message msg)
{
switch(msg.what)
{
/*
* Handling MESSAGE_UPDATE_PROGRESS_BAR:
* 1. Get the current progress, as indicated in the arg1 field
* of the Message.
* 2. Update the progress bar.
*/
case MESSAGE_UPDATE_PROGRESS_BAR:
if(progressDialog != null)
{
int currentProgress = msg.arg1;
progressDialog.setProgress(currentProgress);
}
break;
/*
* Handling MESSAGE_CONNECTING_STARTED:
* 1. Get the URL of the file being downloaded. This is stored
* in the obj field of the Message.
* 2. Create an indeterminate progress bar.
* 3. Set the message that should be sent if user cancels.
* 4. Show the progress bar.
*/
case MESSAGE_CONNECTING_STARTED:
if(msg.obj != null && msg.obj instanceof String)
{
String url = (String) msg.obj;
// truncate the url
if(url.length() > 16)
{
String tUrl = url.substring(0, 15);
tUrl += "...";
url = tUrl;
}
String pdTitle = thisActivity.getString(R.string.progress_dialog_title_connecting);
String pdMsg = thisActivity.getString(R.string.progress_dialog_message_prefix_connecting);
pdMsg += " " + url;
dismissCurrentProgressDialog();
progressDialog = new ProgressDialog(thisActivity);
progressDialog.setTitle(pdTitle);
progressDialog.setMessage(pdMsg);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
// set the message to be sent when this dialog is canceled
Message newMsg = Message.obtain(this, MESSAGE_DOWNLOAD_CANCELED);
progressDialog.setCancelMessage(newMsg);
progressDialog.show();
}
break;
/*
* Handling MESSAGE_DOWNLOAD_STARTED:
* 1. Create a progress bar with specified max value and current
* value 0; assign it to progressDialog. The arg1 field will
* contain the max value.
* 2. Set the title and text for the progress bar. The obj
* field of the Message will contain a String that
* represents the name of the file being downloaded.
* 3. Set the message that should be sent if dialog is canceled.
* 4. Make the progress bar visible.
*/
case MESSAGE_DOWNLOAD_STARTED:
// obj will contain a String representing the file name
if(msg.obj != null && msg.obj instanceof String)
{
int maxValue = msg.arg1;
String fileName = (String) msg.obj;
String pdTitle = thisActivity.getString(R.string.progress_dialog_title_downloading);
String pdMsg = thisActivity.getString(R.string.progress_dialog_message_prefix_downloading);
pdMsg += " " + fileName;
dismissCurrentProgressDialog();
progressDialog = new ProgressDialog(thisActivity);
progressDialog.setTitle(pdTitle);
progressDialog.setMessage(pdMsg);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setProgress(0);
progressDialog.setMax(maxValue);
// set the message to be sent when this dialog is canceled
Message newMsg = Message.obtain(this, MESSAGE_DOWNLOAD_CANCELED);
progressDialog.setCancelMessage(newMsg);
progressDialog.setCancelable(true);
progressDialog.show();
}
break;
/*
* Handling MESSAGE_DOWNLOAD_COMPLETE:
* 1. Remove the progress bar from the screen.
* 2. Display Toast that says download is complete.
*/
case MESSAGE_DOWNLOAD_COMPLETE:
dismissCurrentProgressDialog();
displayMessage(getString(R.string.user_message_download_complete));
break;
/*
* Handling MESSAGE_DOWNLOAD_CANCELLED:
* 1. Interrupt the downloader thread.
* 2. Remove the progress bar from the screen.
* 3. Display Toast that says download is complete.
*/
case MESSAGE_DOWNLOAD_CANCELED:
if(downloaderThread != null)
{
downloaderThread.interrupt();
}
dismissCurrentProgressDialog();
displayMessage(getString(R.string.user_message_download_canceled));
break;
/*
* Handling MESSAGE_ENCOUNTERED_ERROR:
* 1. Check the obj field of the message for the actual error
* message that will be displayed to the user.
* 2. Remove any progress bars from the screen.
* 3. Display a Toast with the error message.
*/
case MESSAGE_ENCOUNTERED_ERROR:
// obj will contain a string representing the error message
if(msg.obj != null && msg.obj instanceof String)
{
String errorMessage = (String) msg.obj;
dismissCurrentProgressDialog();
displayMessage(errorMessage);
}
break;
default:
// nothing to do here
break;
}
}
};
/**
* If there is a progress dialog, dismiss it and set progressDialog to
* null.
*/
public void dismissCurrentProgressDialog()
{
if(progressDialog != null)
{
progressDialog.hide();
progressDialog.dismiss();
progressDialog = null;
}
}
/**
* Displays a message to the user, in the form of a Toast.
* #param message Message to be displayed.
*/
public void displayMessage(String message)
{
if(message != null)
{
Toast.makeText(thisActivity, message, Toast.LENGTH_SHORT).show();
}
}
}
And heres the Log:
Process: com.NautGames.xecta.app, PID: 3032
java.lang.IllegalStateException: Could not find a method onClick(View) in the activity class com.NautGames.xecta.app.MainActivity for onClick handler on view class android.widget.Button with id 'download_button'
at android.view.View$1.onClick(View.java:3810)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.om.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NoSuchMethodException: onClick [class android.view.View]
at java.lang.Class.getConstructorOrMethod(Class.java:472)
at java.lang.Class.getMethod(Class.java:857)
at android.view.View$1.onClick(View.java:3803)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Could anyone tell me what the problem is?
Thanks in advance.
Since you said it's in AndroidFileDownload, I'd suggest you to do as follows:
#Override
public void onClick(View view)
// you need to get the id of the clicked view:
if(view.getId() == R.id.download_button) {
EditText urlInputField = (EditText) thisActivity.findViewById(R.id.url_input);
String urlInput = urlInputField.getText().toString();
downloaderThread = new DownloaderThread(thisActivity, urlInput);
downloaderThread.start();
}
}
This is the cause of: NoSuchMethodException: onClick [class android.view.View]. It means that your onClick method cannot find your button (id) where you did set an onClickListener method.
And then, in the future, I think the problem will be that AndroidFileDownload is not declared in your Manifest file. You should add it as follows:
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.NautGames.xecta.app.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>
// add every activity in your app like this below
<activity
android:name="com.NautGames.xecta.app.AndroidFileDownloader"
android:label="#string/app_name" />
</application>