I am trying to implement Stephen Wylie's Google Drive example (here). Here is my code:
package com.googledrive.googledriveapp;
// For Google Drive / Play Services
// Version 1.1 - Added new comments & removed dead code
// Stephen Wylie - 10/20/2012
import java.io.IOException;
import java.util.ArrayList;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.android.gms.common.AccountPicker;
import com.google.api.client.auth.oauth2.BearerToken;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.android2.AndroidHttp;
import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.json.JsonHttpRequest;
import com.google.api.client.http.json.JsonHttpRequestInitializer;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.Drive.Apps.List;
import com.google.api.services.drive.Drive.Files;
import com.google.api.services.drive.DriveRequest;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;
public class MainActivity extends Activity {
private static final int CHOOSE_ACCOUNT=0;
private static String accountName;
private static int REQUEST_TOKEN=0;
private Button btn_drive;
private Context ctx = this;
private Activity a = this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set up the GUI layout
setContentView(R.layout.activity_main);
// set the variables to access the GUI controls
btn_drive = (Button) findViewById(R.id.btn_drive);
btn_drive.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
chooseAccount();
}
});
}
public void chooseAccount() {
Intent intent = AccountPicker.newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null, null, null, null);
startActivityForResult(intent, CHOOSE_ACCOUNT);
}
// Fetch the access token asynchronously.
void getAndUseAuthTokenInAsyncTask(Account account) {
AsyncTask<Account, String, String> task = new AsyncTask<Account, String, String>() {
ProgressDialog progressDlg;
AsyncTask<Account, String, String> me = this;
#Override
protected void onPreExecute() {
progressDlg = new ProgressDialog(ctx, ProgressDialog.STYLE_SPINNER);
progressDlg.setMax(100);
progressDlg.setTitle("Validating...");
progressDlg.setMessage("Verifying the login data you entered...\n\nThis action will time out after 10 seconds.");
progressDlg.setCancelable(false);
progressDlg.setIndeterminate(false);
progressDlg.setOnCancelListener(new android.content.DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface d) {
progressDlg.dismiss();
me.cancel(true);
}
});
progressDlg.show();
}
#Override
protected String doInBackground(Account... params) {
return getAccessToken(params[0]);
}
#Override
protected void onPostExecute(String s) {
if (s == null) {
// Wait for the extra intent
} else {
accountName = s;
getDriveFiles();
}
progressDlg.dismiss();
}
};
task.execute(account);
}
/**
* Fetches the token from a particular Google account chosen by the user. DO NOT RUN THIS DIRECTLY. It must be run asynchronously inside an AsyncTask.
* #param activity
* #param account
* #return
*/
private String getAccessToken(Account account) {
try {
return GoogleAuthUtil.getToken(ctx, account.name, "oauth2:" + DriveScopes.DRIVE_READONLY); // IMPORTANT: DriveScopes must be changed depending on what level of access you want
} catch (UserRecoverableAuthException e) {
// Start the Approval Screen intent, if not run from an Activity, add the Intent.FLAG_ACTIVITY_NEW_TASK flag.
a.startActivityForResult(e.getIntent(), REQUEST_TOKEN);
e.printStackTrace();
return null;
} catch (GoogleAuthException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private Drive getDriveService() {
HttpTransport ht = AndroidHttp.newCompatibleTransport(); // Makes a transport compatible with both Android 2.2- and 2.3+
JacksonFactory jf = new JacksonFactory(); // You need a JSON parser to help you out with the API response
Credential credential = new Credential(BearerToken.authorizationHeaderAccessMethod()).setAccessToken(accountName);
HttpRequestFactory rf = ht.createRequestFactory(credential);
Drive.Builder b = new Drive.Builder(ht, jf, null);
b.setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
#Override
public void initialize(JsonHttpRequest request) throws IOException {
DriveRequest driveRequest = (DriveRequest) request;
driveRequest.setPrettyPrint(true);
driveRequest.setOauthToken(accountName);
}
});
return b.build();
}
/**
* Obtains a list of all files on the signed-in user's Google Drive account.
*/
private void getDriveFiles() {
Drive service = getDriveService();
Log.d("SiteTrack", "FUNCTION getDriveFiles()");
Files.List request;
try {
request = service.files().list(); // .setQ("mimeType=\"text/plain\"");
} catch (IOException e) {
e.printStackTrace();
return;
}
do {
FileList files;
try {
Log.d("SiteTrack", request.toString());
files = request.execute();
} catch (IOException e) {
e.printStackTrace();
Log.d("SiteTrack", "Exception");
return;
}
ArrayList<File> fileList = (ArrayList<File>) files.getItems();
Log.d("SiteTrack", "Files found: " + files.getItems().size());
for (File f : fileList) {
String fileId = f.getId();
String title = f.getTitle();
Log.d("SiteTrack", "File " + fileId + ": " + title);
}
request.setPageToken(files.getNextPageToken());
} while (request.getPageToken() != null && request.getPageToken().length() >= 0);
}
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
if (requestCode == CHOOSE_ACCOUNT && resultCode == RESULT_OK) {
accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
GoogleAccountManager gam = new GoogleAccountManager(this);
getAndUseAuthTokenInAsyncTask(gam.getAccountByName(accountName));
Log.d("SiteTrack", "CHOOSE_ACCOUNT");
} else if (requestCode == REQUEST_TOKEN && resultCode == RESULT_OK) {
accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
Log.d("SiteTrack", "REQUEST_TOKEN");
}
}
}
Here is my manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.googledrive.googledriveapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="android.app.ActivityGroup" />
</activity>
</application>
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
Here is my activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btn_drive"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Connect to Google Drive" />
</LinearLayout>
And here is the LogCat error I receive. It occurs when the button is pressed:
10-28 00:25:28.637: E/AndroidRuntime(842): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=com.google.android.gms.common.account.CHOOSE_ACCOUNT (has extras) }
10-28 00:25:28.637: E/AndroidRuntime(842): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1512)
10-28 00:25:28.637: E/AndroidRuntime(842): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1384)
10-28 00:25:28.637: E/AndroidRuntime(842): at android.app.Activity.startActivityForResult(Activity.java:3190)
10-28 00:25:28.637: E/AndroidRuntime(842): at com.googledrive.googledriveapp.MainActivity.chooseAccount(MainActivity.java:67)
10-28 00:25:28.637: E/AndroidRuntime(842): at com.googledrive.googledriveapp.MainActivity$1.onClick(MainActivity.java:60)
10-28 00:25:28.637: E/AndroidRuntime(842): at android.view.View.performClick(View.java:3511)
10-28 00:25:28.637: E/AndroidRuntime(842): at android.view.View$PerformClick.run(View.java:14105)
10-28 00:25:28.637: E/AndroidRuntime(842): at android.os.Handler.handleCallback(Handler.java:605)
10-28 00:25:28.637: E/AndroidRuntime(842): at android.os.Handler.dispatchMessage(Handler.java:92)
10-28 00:25:28.637: E/AndroidRuntime(842): at android.os.Looper.loop(Looper.java:137)
10-28 00:25:28.637: E/AndroidRuntime(842): at android.app.ActivityThread.main(ActivityThread.java:4424)
10-28 00:25:28.637: E/AndroidRuntime(842): at java.lang.reflect.Method.invokeNative(Native Method)
10-28 00:25:28.637: E/AndroidRuntime(842): at java.lang.reflect.Method.invoke(Method.java:511)
10-28 00:25:28.637: E/AndroidRuntime(842): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
10-28 00:25:28.637: E/AndroidRuntime(842): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
10-28 00:25:28.637: E/AndroidRuntime(842): at dalvik.system.NativeStart.main(Native Method)
Can anyone help out?
We've been doing some experimenting, and our current theory is that the new Google OAuth Library depends on having the latest version of Google Play.
We found that if your device still has the Android Marketplace, or an older Google Play we couldn't get OAuth to work.
So you might try opening the Android Marketplace or Google Play App to kick off an upgrade.
Open the Android Marketplace, Accept the Upgrade to Google Play.
Close the Marketplace, and open the Google Play App.
Accept the Terms of Service for Google Play.
Wait a few seconds, sacrifice a chicken, and then you should be able to run Google OAuth.
EDIT: Looks like Google Provides some guidance on what your app should do if your users are missing the correct Google Play version. See: https://developer.android.com/google/play-services/setup.html#ensure
Google Drive API seems (acording to the Google people) to only works on a real Device, in the Emulator it will crash with this error.
So my Advice, try on a real device.
Related
I was trying to make an app to capture an image and store it in the file. There is no error while building the project but the app does not run on the AVD Pixel 2 API 24
This is the code for MainActivity.java :
package com.example.myapplication;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
Button button;
File photoFile = null;
static final int CAPTURE_IMAGE_REQUEST = 1;
String mCurrentPhotoPath;
private static final String IMAGE_DIRECTORY_NAME = "MyApp";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
button = findViewById(R.id.btnCaptureImage);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
captureImage();
}
else
{
captureImage2();
}
}
});
}
/* Capture Image function for 4.4.4 and lower. Not tested for Android Version 3 and 2 */
private void captureImage2() {
try {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
photoFile = createImageFile4();
if(photoFile!=null)
{
displayMessage(getBaseContext(),photoFile.getAbsolutePath());
Log.i("MyApp",photoFile.getAbsolutePath());
Uri photoURI = Uri.fromFile(photoFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(cameraIntent, CAPTURE_IMAGE_REQUEST);
}
}
catch (Exception e)
{
displayMessage(getBaseContext(),"Camera is not available."+e.toString());
}
}
private void captureImage()
{
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);
}
else
{
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
try {
photoFile = createImageFile();
displayMessage(getBaseContext(),photoFile.getAbsolutePath());
Log.i("MyApp",photoFile.getAbsolutePath());
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.MyApplication.MainActivity",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAPTURE_IMAGE_REQUEST);
}
} catch (Exception ex) {
// Error occurred while creating the File
displayMessage(getBaseContext(), ex.getMessage());
}
}else
{
displayMessage(getBaseContext(),"Null");
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//Bundle extras = data.getExtras();
//Bitmap imageBitmap = (Bitmap) extras.get("data");
//imageView.setImageBitmap(imageBitmap);
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAPTURE_IMAGE_REQUEST && resultCode == RESULT_OK) {
Bitmap myBitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
imageView.setImageBitmap(myBitmap);
} else {
displayMessage(getBaseContext(), "Request cancelled or something went wrong.");
}
}
private File createImageFile4()
{
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
displayMessage(getBaseContext(),"Unable to create directory.");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss",
Locale.getDefault()).format(new Date());
return new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
}
private File createImageFile() throws IOException {
// Create an image file name
#SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private void displayMessage(Context context, String message)
{
Toast.makeText(context,message,Toast.LENGTH_LONG).show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == 0) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
captureImage();
}
}
}
and this is the code for AndroidManifest.xml
<?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.example.myapplication">
<uses-feature android:name="android.hardware.camera"
android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera2.params.Face" />
<application
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:ignore="AllowBackup">
<provider
android:name="android.content.SearchRecentSuggestionsProvider"
android:authorities="com.example.myapplication.MainActivity"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths">
</meta-data>
</provider>
<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>
but the logcat errors show
2020-04-25 21:45:03.945 4722-4724/? A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0xa8 in
tid 4724 (Binder:4722_2)
--------- beginning of system
2020-04-25 21:45:06.581 4726-4726/? E/memtrack: Couldn't load memtrack module (No such file or directory)
2020-04-25 21:45:06.581 4726-4726/? E/android.os.Debug: failed to load memtrack module: -2
2020-04-25 21:45:06.583 4716-4716/? E/memtrack: Couldn't load memtrack module (No such file or directory)
2020-04-25 21:45:06.583 4716-4716/? E/android.os.Debug: failed to load memtrack module: -2
2020-04-25 21:45:07.949 4746-4746/? E/memtrack: Couldn't load memtrack module (No such file or directory)
2020-04-25 21:45:07.949 4746-4746/? E/android.os.Debug: failed to load memtrack module: -2
2020-04-25 21:45:08.585 4755-4755/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 4755
java.lang.RuntimeException: Unable to get provider android.content.SearchRecentSuggestionsProvider:
java.lang.IllegalArgumentException: Provider not configured
at android.app.ActivityThread.installProvider(ActivityThread.java:5814)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:5403)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5342)
at android.app.ActivityThread.-wrap2(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1528)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.IllegalArgumentException: Provider not configured
at
android.content.SearchRecentSuggestionsProvider.onCreate(SearchRecentSuggestionsProvider.java:305)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1751)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1726)
at android.app.ActivityThread.installProvider(ActivityThread.java:5811)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:5403)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5342)
at android.app.ActivityThread.-wrap2(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1528)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
2020-04-25 21:45:09.728 1318-1318/? E/EGL_emulation: tid 1318: eglCreateSyncKHR(1901): error 0x3004
(EGL_BAD_ATTRIBUTE)
It would be really helpful if I would be helped in finding a solution to this problem.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
MainActivity.java
package com.example.yashpachisia.fetchjson;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends ActionBarActivity {
String myJSON;
private static final String TAG_RESULTS="result";
private static final String TAG_NAME = "name";
private static final String TAG_AGE = "age";
private static final String TAG_SEX ="sex";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
getData();
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String name = c.getString(TAG_NAME);
String age = c.getString(TAG_AGE);
String sex = c.getString(TAG_SEX);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_NAME,name);
persons.put(TAG_AGE,age);
persons.put(TAG_SEX,sex);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, personList, R.layout.list_item,
new String[]{TAG_NAME,TAG_AGE,TAG_SEX},
new int[]{R.id.name, R.id.age, R.id.sex}
);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://localhost/test/form.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_user) {
return true;
}
return super.onOptionsItemSelected(item);
}*/
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.yashpachisia.fetchjson">
<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">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Logcat window
12-19 17:17:59.353 5132-5132/? D/OpenGLRenderer: Enabling debug mode 0
12-19 17:17:59.353 5132-5132/? D/AndroidRuntime: Shutting down VM
12-19 17:17:59.357 5132-5132/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa6299288)
12-19 17:17:59.357 5132-5132/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:154)
at org.json.JSONObject.<init>(JSONObject.java:171)
at com.example.yashpachisia.fetchjson.MainActivity.showList(MainActivity.java:56)
at com.example.yashpachisia.fetchjson.MainActivity$1GetDataJSON.onPostExecute(MainActivity.java:128)
at com.example.yashpachisia.fetchjson.MainActivity$1GetDataJSON.onPostExecute(MainActivity.java:89)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
call this method showList() only after checking the result you get in onPostExecute() is not null or empty
if(result != null && result.length >0 ){
myJSON=result;
showList()
}
as your myJson could be empty you are trying to run Json code on it, due to which you are getting NulPointerError
Update
if you are getting the null value it means, that you are not getting the data from the web service or you are calling it wrong.
I saw some mistakes in your code so i wrote you a new one. my code uses commons-io-2.4.jar library but you can always write your own code to see the result
String chartString = "your url which you want to call";
URL chartURL = new URL(chartString);
HttpURLConnection chartHttpURLConnection = (HttpURLConnection) chartURL.openConnection();
chartHttpURLConnection.connect();
String result = IOUtils.toString(chartHttpURLConnection.getInputStream());
System.out.println(""+result);
as you are trying to call the local serve though emulator so the IP address would be 10.0.2.2
so your URL which you would be calling is
URL url = new URL(http://10.0.2.2/test/form.php);
have a look at this IP Address for the Emulator
Trying to create an android application to record video and capture images. I've followed the tutorials thus far with some success however I must have a lack of knowledge about the android sdk to not be able to get around this issue. No doubt I will feel stupid once someone figures this out but I'm here to learn in the end.
Here is the MainActivity.java
package example.myapplication;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
public MainActivity(Context context) {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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_main, menu);
return true;
}
/** Check if this device has a camera */
public boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
#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.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is the CameraPreview.java
package example.myapplication;
import android.content.Context;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.Button;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
/** A basic Camera preview class */
public class CameraPreview extends MainActivity implements SurfaceHolder.Callback {
private android.hardware.Camera.PictureCallback mPicture;
private Camera mCamera;
private CameraPreview mPreview;
private SurfaceHolder mHolder;
private SurfaceHolder holder;
public void setContentView(int activity_camera) {}
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;
private static final String TAG = "CameraPreview";
public CameraPreview(Context context, Camera camera) {
super(context);
mCamera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
mCamera.setDisplayOrientation(90);
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (mHolder.getSurface() == null){
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e){
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null){
Log.d(TAG, "Error creating media file, check storage permissions: ");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HH:mm:ss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
public void onClick() {
// Add a listener to the Capture button
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0){
// get an image from the camera
mCamera.takePicture(null, null, mPicture);
}
});
}
public SurfaceHolder getHolder() {
return holder;
}
public void setHolder(SurfaceHolder holder) {
this.holder = holder;
}
}
Here is the AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="example.myapplication" >
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera2" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<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" >
<activity
android:name=".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>
</manifest>
and the logcat
Process: example.myapplication, PID: 20671
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{example.myapplication/example.myapplication.MainActivity}: java.lang.InstantiationException: can't instantiate class example.myapplication.MainActivity; no empty constructor
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2514)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2653)
at android.app.ActivityThread.access$800(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5872)
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:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.InstantiationException: can't instantiate class installation04.myapplication.MainActivity; no empty constructor
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2505)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2653)
at android.app.ActivityThread.access$800(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1355)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5872)
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:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
at dalvik.system.NativeStart.main(Native Method)
A couple of things that need to be sorted:
Please remove all constructors from classes that extend Activity. - Activities do not work this way. Please look read how Activity Life cycle works.
Please add the CameraPreview activity to your manifest as well.
delete MainActivity constructor
public MainActivity(Context context) {
}
Please read carefully the stacktrace:
java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{example.myapplication/example.myapplication.MainActivity}:
java.lang.InstantiationException: can't instantiate class
example.myapplication.MainActivity; no empty constructor
You have created constructor in your Activity. Remove the constructor from your Activities and use the Lifecycle callbacks.
As per android guidelines you should not create constructor in the Activity classes since android OS creates object of Activity classes and it use the default empty constructor of the class to create object.
This question already has answers here:
Broadcast Receiver as inner class in Android
(6 answers)
Closed 7 years ago.
I'm trying to do a simple web view app based with push notifications. My app registers in background and do all the stuff, but when I send a push and my phone is supposed to show the push notification the app crashes. I've tried to debug and set a breakpoint in the onReceive() method, and I've also set breakpoints everywere but the app just crashes and don't stop anywere before doing it. I'm new in android studio and I don't understand at all the error messages so please if somebody can help me to find the error it would be greatly appreciated.
logCat:
05-04 14:41:46.349 30089-30089/com.example.alfredo.guiasandroid E/dalvikvm﹕ Could not find class 'android.app.Notification$Builder', referenced from method com.google.android.gms.common.GooglePlayServicesUtil.zza
05-04 14:41:46.349 30089-30089/com.example.alfredo.guiasandroid E/dalvikvm﹕ Could not find class 'android.app.AppOpsManager', referenced from method com.google.android.gms.common.GooglePlayServicesUtil.zza
05-04 14:43:34.879 10207-10207/? E/Launcher﹕ setWindowOpaque()
05-04 14:43:34.909 10207-10207/? E/Launcher﹕ MTP-LAUNCHER: media scanning not yet finished.
05-04 14:43:34.959 10207-10207/? E/Launcher﹕ setWindowOpaque()
05-04 14:43:44.879 30089-30089/com.example.alfredo.guiasandroid E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate receiver com.example.alfredo.guiasandroid.MainActivity$GcmBroadcastReceiver: java.lang.InstantiationException: com.example.alfredo.guiasandroid.MainActivity$GcmBroadcastReceiver
at android.app.ActivityThread.handleReceiver(ActivityThread.java:1777)
at android.app.ActivityThread.access$2400(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:985)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3687)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.InstantiationException: com.example.alfredo.guiasandroid.MainActivity$GcmBroadcastReceiver
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1409)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:1768)
at android.app.ActivityThread.access$2400(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:985)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3687)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
at dalvik.system.NativeStart.main(Native Method)
05-04 14:43:44.979 10104-10118/? E/﹕ Dumpstate > /data/log/dumpstate_app_error
05-04 14:43:50.839 10207-10207/? E/Launcher﹕ setWindowOpaque()
mainfest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.alfredo.guiasandroid" android:versionCode="1" android:versionName="1.0">
<uses-sdk android:minSdkVersion="10" android:targetSdkVersion="22"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<permission android:name="com.example.alfredo.guiasandroid.permission.C2D_MESSAGE"
android:protectionLevel="signature"/>
<uses-permission android:name="com.example.alfredo.guiasandroid.permission.C2D_MESSAGE"/>
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<application
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name">
<!-- Required for applications which use Google Play Services. -->
<!-- <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" />
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:configChanges="orientation|keyboardHidden|screenSize"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".MainActivity$GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<!--android:name=".MainActivity$GcmBroadcastReceiver" -->
<intent-filter>
<!--
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="com.example.alfredo.webapp" />
-->
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.example.alfredo.guiasandroid" />
</intent-filter>
</receiver>
<!--
<service android:name=".MainActivity$GcmIntentService" />
-->
<service android:name=".MainActivity$GcmIntentService" />
</application>
</manifest>
<!--
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.alfredo.guiasandroid" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".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>
</manifest>
-->
build.gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
defaultConfig {
applicationId "com.example.alfredo.guiasandroid"
minSdkVersion 10
targetSdkVersion 22
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.1.1'
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.0.0'
compile 'com.google.android.gms:play-services:7.0.0'
}
mainActivity.java:
package com.example.alfredo.guiasandroid;
import android.os.Bundle;
import android.view.MenuItem;
import android.support.v4.app.NotificationCompat;
import android.app.Activity;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.atomic.AtomicInteger;
public class MainActivity extends Activity {
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
String SENDER_ID = "example_Number";
/**
* Tag used on log messages.
*/
static final String TAG = "GCMDemo";
private WebView myWebView = null;
TextView mDisplay;
GoogleCloudMessaging gcm;
AtomicInteger msgId = new AtomicInteger();
SharedPreferences prefs;
Context context;
String regid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "hola coño");
setContentView(R.layout.activity_main);
//initialize variables
context = getApplicationContext();
gcm = GoogleCloudMessaging.getInstance(this);
prefs = getPreferences(0);
mDisplay = new TextView(getApplicationContext());
// web view
this.myWebView = (WebView) findViewById(R.id.activity_main_webview);
myWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("http://mongini.net/guiasdelsur");
//remove shared prefs
/*
SharedPreferences prefs = getGCMPreferences(context);
SharedPreferences.Editor edit = prefs.edit();
edit.clear();
edit.commit();
*/
/*
SharedPreferences clear_cache = getSharedPreferences("registration_id", MODE_PRIVATE);
SharedPreferences.Editor edit = clear_cache.edit();
edit.clear();
edit.commit();
*/
// Check device for Play Services APK. If check succeeds, proceed with
// GCM registration.
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(this);
regid = getRegistrationId(context);
if (regid.isEmpty()) {
registerInBackground();
Log.i(TAG,"ok");
}
} else {
Log.i(TAG, "No valid Google Play Services APK found.");
}
}
// You need to do the Play Services APK check here too.
#Override
protected void onResume() {
super.onResume();
checkPlayServices();
}
/**
* Check the device to make sure it has the Google Play Services APK. If
* it doesn't, display a dialog that allows users to download the APK from
* the Google Play Store or enable it in the device's system settings.
*/
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.d(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}
/**
* Gets the current registration ID for application on GCM service.
* <p>
* If result is empty, the app needs to register.
*
* #return registration ID, or empty string if there is no existing
* registration ID.
*/
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing registration ID is not guaranteed to work with
// the new app version.
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
/**
* #return Application's {#code SharedPreferences}.
*/
private SharedPreferences getGCMPreferences(Context context) {
// This sample app persists the registration ID in shared preferences, but
// how you store the registration ID in your app is up to you.
return getSharedPreferences(MainActivity.class.getSimpleName(),
Context.MODE_PRIVATE);
}
/**
* #return Application's version code from the {#code PackageManager}.
*/
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
/**
* Registers the application with GCM servers asynchronously.
* <p>
* Stores the registration ID and app versionCode in the application's
* shared preferences. com.example.alfredo.webapp.MainActivity
*/
private void registerInBackground() {
new AsyncTask<Void,Void,String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration id=" + regid;
// You should send the registration ID to your server over HTTP,
// so it can use GCM/HTTP or CCS to send messages to your app.
sendRegistrationIdToBackend();
// Save the regid for future use - no need to register again.
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regid);
editor.commit();
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
// Once registration is done, display the registration status
// string in the Activity's UI.
#Override
protected void onPostExecute(String msg) {
mDisplay.append(msg + "\n");
}
}.execute();
}
private 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 "";
}
}
/**
* Sends the registration ID to your server over HTTP, so it can use GCM/HTTP
* or CCS to send messages to your app. Not needed for this demo since the
* device sends upstream messages to a server that echoes back the message
* using the 'from' address in the message.
*/
private void sendRegistrationIdToBackend() {
// Your implementation here.
HttpURLConnection urlConnection = null;
try {
URL url = new URL("http://www.example.com/example.php?host=localhost&dbname=db_name&user=user&pass=pass&idPush="+regid);
urlConnection = (HttpURLConnection) url.openConnection();
/** Connecting to url */
urlConnection.connect();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
}catch(Exception e){
Log.d("Exception url ", e.toString());
}finally {
urlConnection.disconnect();
}
}
/**
* Stores the registration ID and app versionCode in the application's
* {#code SharedPreferences}.
*
* #param context application's context.
* #param regId registration ID
*/
//aqui peta
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGCMPreferences(context);
int appVersion = getAppVersion(context);
Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public GcmIntentService() {
super("GcmIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that GCM
* will be extended in the future with new message types, just ignore
* any message types you're not interested in, or that you don't
* recognize.
*/
if (GoogleCloudMessaging.
MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_DELETED.equals(messageType)) {
sendNotification("Deleted messages on server: " +
extras.toString());
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// This loop represents the service doing some work.
for (int i=0; i<5; i++) {
Log.i(TAG, "Working... " + (i+1)
+ "/5 # " + SystemClock.elapsedRealtime());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
Log.i(TAG, "Completed work # " + SystemClock.elapsedRealtime());
// Post notification of received message.
sendNotification("Received: " + extras.toString());
Log.i(TAG, "Received: " + extras.toString());
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
// Put the message into a notification and post it.
// This is just one simple example of what you might choose to do with
// a GCM message.
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
//.setSmallIcon(R.drawable.ic_stat_gcm)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
//back device button
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && this.myWebView.canGoBack()) {
this.myWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
#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.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
AFAIK the inner-class BroadcastReceivers only work if they are static.
In fact $ marks a static inner-class.
See https://stackoverflow.com/a/4392499/603270
I have been trying to learn how Google Cloud Messaging works in Android apps, specifically multicast messaging, so I found a tutorial with source code. Unfortunately I can get the program to compile without error but when it runs, I get a fatal exception. Anyone know what is wrong?
Here is the main activity:
package com.ganyo.pushtest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gcm.GCMRegistrar;
import static com.ganyo.pushtest.Util.*;
import static com.ganyo.pushtest.Util.TAG;
public class PushMainActivity extends Activity {
private TextView messageTextView;
private Button sendButton;
private AlertDialogManager alert = new AlertDialogManager();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// this is a hack to force AsyncTask to be initialized on main thread. Without this things
// won't work correctly on older versions of Android (2.2, apilevel=8)
try {
Class.forName("android.os.AsyncTask");
} catch (Exception ignored) {}
GCMRegistrar.checkDevice(this);
GCMRegistrar.checkManifest(this);
initUI();
AppServices.loginAndRegisterForPush(this);
}
private void initUI() {
setContentView(R.layout.main);
messageTextView = (TextView)findViewById(R.id.lblMessage);
sendButton = (Button)findViewById(R.id.sendButton);
sendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AppServices.sendMyselfANotification(v.getContext());
}
});
registerReceiver(notificationReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION));
}
/**
* Receives push Notifications
* */
private final BroadcastReceiver notificationReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Waking up mobile if it is sleeping
WakeLocker.acquire(getApplicationContext());
/**
* Take some action upon receiving a push notification here!
**/
String message = intent.getExtras().getString(EXTRA_MESSAGE);
if (message == null) { message = "Empty Message"; }
Log.i(TAG, message);
messageTextView.append("\n" + message);
alert.showAlertDialog(context, getString(R.string.gcm_alert_title), message);
Toast.makeText(getApplicationContext(), getString(R.string.gcm_message, message), Toast.LENGTH_LONG).show();
WakeLocker.release();
}
};
// this will be called when the screen rotates instead of onCreate()
// due to manifest setting, see: android:configChanges
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
initUI();
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(notificationReceiver);
}
}
Here is the manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ganyo.pushtest"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="16"/>
<permission android:name="com.ganyo.pushtest.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="com.ganyo.pushtest.permission.C2D_MESSAGE" />
<!-- App receives GCM messages. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<!-- GCM connects to Google Services. -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<application android:label="#string/app_name" android:icon="#drawable/ic_launcher">
<activity android:name="com.ganyo.pushtest.PushMainActivity"
android:label="#string/app_name"
android:configChanges="keyboardHidden|orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<receiver android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.ganyo.pushtest" />
</intent-filter>
</receiver>
<service android:name="GCMIntentService" />
</application>
</manifest>
Here is Appservices:
package com.ganyo.pushtest;
import android.content.Context;
import android.util.Log;
import com.apigee.sdk.ApigeeClient;
import com.apigee.sdk.data.client.DataClient;
import com.apigee.sdk.data.client.callbacks.ApiResponseCallback;
import com.apigee.sdk.data.client.callbacks.DeviceRegistrationCallback;
import com.apigee.sdk.data.client.entities.Device;
import com.apigee.sdk.data.client.entities.Entity;
import com.apigee.sdk.data.client.response.ApiResponse;
import com.apigee.sdk.data.client.utils.JsonUtils;
import com.google.android.gcm.GCMRegistrar;
import com.apigee.sdk.data.client.push.GCMPayload;
import com.apigee.sdk.data.client.push.GCMDestination;
import java.util.HashMap;
import static com.ganyo.pushtest.Util.*;
import static com.ganyo.pushtest.Settings.*;
public final class AppServices {
private static DataClient client;
private static Device device;
static synchronized DataClient getClient(Context context) {
if (client == null) {
if (ORG.equals("<<your org name here>>")) {
Log.e(TAG, "ORG value has not been set.");
} else {
ApigeeClient apigeeClient = new ApigeeClient(ORG,APP,API_URL,context);
client = apigeeClient.getDataClient();
}
}
return client;
}
static void loginAndRegisterForPush(final Context context) {
if ((USER != null) && (USER.length() > 0)) {
DataClient dataClient = getClient(context);
if (dataClient != null) {
dataClient.authorizeAppUserAsync(USER, PASSWORD, new ApiResponseCallback() {
#Override
public void onResponse(ApiResponse apiResponse) {
Log.i(TAG, "login response: " + apiResponse);
registerPush(context);
}
#Override
public void onException(Exception e) {
displayMessage(context, "Login Exception: " + e);
Log.i(TAG, "login exception: " + e);
}
});
} else {
Log.e(TAG,"Data client is null, did you set ORG value in Settings.java?");
}
} else {
registerPush(context);
}
}
static void registerPush(Context context) {
final String regId = GCMRegistrar.getRegistrationId(context);
if ("".equals(regId)) {
GCMRegistrar.register(context, Settings.GCM_SENDER_ID);
} else {
if (GCMRegistrar.isRegisteredOnServer(context)) {
Log.i(TAG, "Already registered with GCM");
} else {
AppServices.register(context, regId);
}
}
}
/**
* Register this user/device pair on App Services.
*/
static void register(final Context context, final String regId) {
Log.i(TAG, "registering device: " + regId);
DataClient dataClient = getClient(context);
if (dataClient != null) {
dataClient.registerDeviceForPushAsync(dataClient.getUniqueDeviceID(), NOTIFIER, regId, null, new DeviceRegistrationCallback() {
#Override
public void onResponse(Device device) {
Log.i(TAG, "register response: " + device);
AppServices.device = device;
displayMessage(context, "Device registered as: " + regId);
DataClient dataClient = getClient(context);
if (dataClient != null) {
// connect Device to current User - if there is one
if (dataClient.getLoggedInUser() != null) {
dataClient.connectEntitiesAsync("users", dataClient.getLoggedInUser().getUuid().toString(),
"devices", device.getUuid().toString(),
new ApiResponseCallback() {
#Override
public void onResponse(ApiResponse apiResponse) {
Log.i(TAG, "connect response: " + apiResponse);
}
#Override
public void onException(Exception e) {
displayMessage(context, "Connect Exception: " + e);
Log.i(TAG, "connect exception: " + e);
}
});
}
} else {
Log.e(TAG,"data client is null, did you set ORG value in Settings.java?");
}
}
#Override
public void onException(Exception e) {
displayMessage(context, "Register Exception: " + e);
Log.i(TAG, "register exception: " + e);
}
#Override
public void onDeviceRegistration(Device device) { /* this won't ever be called */ }
});
} else {
Log.e(TAG, "Data client is null, did you set ORG value in Settings.java?");
}
}
static void sendMyselfANotification(final Context context) {
if (device == null) {
displayMessage(context, "Device not registered. ORG value set in Settings.java?");
} else {
DataClient dataClient = getClient(context);
if (dataClient != null) {
GCMDestination destination = GCMDestination.destinationSingleDevice(device.getUuid());
GCMPayload payload = new GCMPayload();
payload.setAlertText("Hi there!");
dataClient.pushNotificationAsync(payload, destination, "google", new ApiResponseCallback() {
#Override
public void onResponse(ApiResponse apiResponse) {
Log.i(TAG, "send response: " + apiResponse);
}
#Override
public void onException(Exception e) {
displayMessage(context, "Send Exception: " + e);
Log.i(TAG, "send exception: " + e);
}
});
} else {
Log.e(TAG, "data client is null, did you set ORG value in Settings.java?");
}
}
}
/**
* Unregister this device within the server.
*/
static void unregister(final Context context, final String regId) {
Log.i(TAG, "unregistering device: " + regId);
register(context, "");
}
}
Gmcintentservices:
package com.ganyo.pushtest;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import com.google.android.gcm.GCMBaseIntentService;
import static com.ganyo.pushtest.Settings.GCM_SENDER_ID;
import static com.ganyo.pushtest.Util.displayMessage;
public class GCMIntentService extends GCMBaseIntentService {
public GCMIntentService() {
super(GCM_SENDER_ID);
}
/**
* Method called on device registered
**/
#Override
protected void onRegistered(Context context, String registrationId) {
Log.i(TAG, "Device registered: " + registrationId);
displayMessage(context, getString(R.string.gcm_registered, registrationId));
AppServices.register(context, registrationId);
}
/**
* Method called on device unregistered
* */
#Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "Device unregistered");
displayMessage(context, getString(R.string.gcm_unregistered, registrationId));
AppServices.unregister(context, registrationId);
}
/**
* Method called on receiving a new message
* */
#Override
protected void onMessage(Context context, Intent intent) {
String message = intent.getExtras().getString("data");
Log.i(TAG, "Received message: " + message);
displayMessage(context, message);
generateNotification(context, message);
}
/**
* Method called on receiving a deleted message
* */
#Override
protected void onDeletedMessages(Context context, int total) {
Log.i(TAG, "Received deleted messages notification");
String message = getString(R.string.gcm_deleted, total);
displayMessage(context, message);
generateNotification(context, message);
}
/**
* Method called on Error
* */
#Override
public void onError(Context context, String errorId) {
Log.i(TAG, "Received error: " + errorId);
displayMessage(context, getString(R.string.gcm_error, errorId));
}
#Override
protected boolean onRecoverableError(Context context, String errorId) {
Log.i(TAG, "Received recoverable error: " + errorId);
displayMessage(context, getString(R.string.gcm_recoverable_error, errorId));
return super.onRecoverableError(context, errorId);
}
/**
* Issues a Notification to inform the user that server has sent a message.
*/
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, PushMainActivity.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(context)
.setContentText(message)
.setContentTitle(context.getString(R.string.app_name))
.setSmallIcon(icon)
.setWhen(when)
.setContentIntent(intent)
.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
}
Alertdialoguemanager:
package com.ganyo.pushtest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
public class AlertDialogManager {
public void showAlertDialog(Context context, String title, String message) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
}
Util:
package com.ganyo.pushtest;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.google.android.gcm.GCMRegistrar;
public final class Util {
static final String TAG = "com.ganyo.pushtest";
static final String DISPLAY_MESSAGE_ACTION = "com.ganyo.pushtest.DISPLAY_MESSAGE";
static final String EXTRA_MESSAGE = "message";
static void displayMessage(Context context, String message) {
Intent intent = new Intent(DISPLAY_MESSAGE_ACTION);
intent.putExtra(EXTRA_MESSAGE, message);
context.sendBroadcast(intent);
}
}
Wakelocker:
package com.ganyo.pushtest;
import android.content.Context;
import android.os.PowerManager;
public abstract class WakeLocker {
private static PowerManager.WakeLock wakeLock;
public static void acquire(Context context) {
if (wakeLock != null) wakeLock.release();
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.ON_AFTER_RELEASE |
PowerManager.ACQUIRE_CAUSES_WAKEUP |
PowerManager.ON_AFTER_RELEASE |
PowerManager.SCREEN_DIM_WAKE_LOCK, "WakeLock");
wakeLock.acquire();
}
public static void release() {
if (wakeLock != null) wakeLock.release(); wakeLock = null;
}
}
Here is the logcat area of the fatal exception:
05-01 00:26:52.757: D/AndroidRuntime(166): Shutting down VM
05-01 00:26:52.777: D/jdwp(166): adbd disconnected
05-01 00:26:52.817: I/AndroidRuntime(166): NOTE: attach of thread 'Binder Thread #3' failed
05-01 00:26:53.050: I/ActivityThread(258): Publishing provider com.svox.pico.providers.SettingsProvider: com.svox.pico.providers.SettingsProvider
05-01 00:26:53.627: I/ActivityManager(58): Start proc com.ganyo.pushtest for activity com.ganyo.pushtest/.PushMainActivity: pid=267 uid=10036 gids={3003}
05-01 00:26:54.687: W/WindowManager(58): No window to dispatch pointer action 0
05-01 00:26:54.707: W/WindowManager(58): No window to dispatch pointer action 1
05-01 00:26:55.467: D/AndroidRuntime(267): Shutting down VM
05-01 00:26:55.467: W/dalvikvm(267): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
05-01 00:26:55.537: E/AndroidRuntime(267): FATAL EXCEPTION: main
05-01 00:26:55.537: E/AndroidRuntime(267): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.ganyo.pushtest/com.ganyo.pushtest.PushMainActivity}: java.lang.ClassNotFoundException: com.ganyo.pushtest.PushMainActivity in loader dalvik.system.PathClassLoader[/data/app/com.ganyo.pushtest-2.apk]
05-01 00:26:55.537: E/AndroidRuntime(267): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
05-01 00:26:55.537: E/AndroidRuntime(267): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
05-01 00:26:55.537: E/AndroidRuntime(267): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
05-01 00:26:55.537: E/AndroidRuntime(267): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
05-01 00:26:55.537: E/AndroidRuntime(267): at android.os.Handler.dispatchMessage(Handler.java:99)
05-01 00:26:55.537: E/AndroidRuntime(267): at android.os.Looper.loop(Looper.java:123)
05-01 00:26:55.537: E/AndroidRuntime(267): at android.app.ActivityThread.main(ActivityThread.java:4627)
05-01 00:26:55.537: E/AndroidRuntime(267): at java.lang.reflect.Method.invokeNative(Native Method)
05-01 00:26:55.537: E/AndroidRuntime(267): at java.lang.reflect.Method.invoke(Method.java:521)
05-01 00:26:55.537: E/AndroidRuntime(267): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-01 00:26:55.537: E/AndroidRuntime(267): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-01 00:26:55.537: E/AndroidRuntime(267): at dalvik.system.NativeStart.main(Native Method)
05-01 00:26:55.537: E/AndroidRuntime(267): Caused by: java.lang.ClassNotFoundException: com.ganyo.pushtest.PushMainActivity in loader dalvik.system.PathClassLoader[/data/app/com.ganyo.pushtest-2.apk]
05-01 00:26:55.537: E/AndroidRuntime(267): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:243)
05-01 00:26:55.537: E/AndroidRuntime(267): at java.lang.ClassLoader.loadClass(ClassLoader.java:573)
05-01 00:26:55.537: E/AndroidRuntime(267): at java.lang.ClassLoader.loadClass(ClassLoader.java:532)
05-01 00:26:55.537: E/AndroidRuntime(267): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
05-01 00:26:55.537: E/AndroidRuntime(267): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
05-01 00:26:55.537: E/AndroidRuntime(267): ... 11 more
05-01 00:26:55.617: W/ActivityManager(58): Force finishing activity com.ganyo.pushtest/.PushMainActivity
05-01 00:26:56.499: W/ActivityManager(58): Activity pause timeout for HistoryRecord{460133f8 com.ganyo.pushtest/.PushMainActivity}
05-01 00:26:56.687: I/ARMAssembler(58): generated scanline__00000077:03515104_00000000_00000000 [ 33 ipp] (47 ins) at [0x3261a0:0x32625c] in 1336038 ns
05-01 00:26:56.777: I/ARMAssembler(58): generated scanline__00000177:03515104_00001001_00000000 [ 91 ipp] (114 ins) at [0x3265b8:0x326780] in 1506105 ns
05-01 00:26:57.337: I/ARMAssembler(58): generated scanline__00000077:03545404_00000004_00000000 [ 47 ipp] (67 ins) at [0x326788:0x326894] in 951792 ns
05-01 00:26:57.967: D/AndroidRuntime(271): >>>>>>>>>>>>>> AndroidRuntime START <<<<<<<<<<<<<<
05-01 00:26:58.009: D/AndroidRuntime(271): CheckJNI is ON
05-01 00:27:00.377: D/AndroidRuntime(271): --- registering native functions ---
Thanks for the help!
It turned out to be all the .java files in the java folder. Once I redid them in the src path, the program worked correctly.