In my app I'm trying to take a picture and send it over to the server coded as a String when I run it, I am able to take the picture but as soon as I click ok the app crashes and I get the following error:
E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/Pictures/test123.jpeg: open failed: EACCES (Permission denied)
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: info.androidhive.loginandregistration, PID: 8775
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, int, java.io.OutputStream)' on a null object reference
at info.androidhive.loginandregistration.activity.ImageActivity$Encode_image.doInBackground(ImageActivity.java:86)
at info.androidhive.loginandregistration.activity.ImageActivity$Encode_image.doInBackground(ImageActivity.java:79)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Heres my code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="info.androidhive.loginandregistration"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET" />
<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.READ_EXTERNAL_STORAGE" />
<application
android:name="info.androidhive.loginandregistration.app.AppController"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".activity.LoginActivity"
android:label="#string/app_name"
android:launchMode="singleTop"
android:windowSoftInputMode="adjustPan" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".activity.RegisterActivity"
android:label="#string/app_name"
android:launchMode="singleTop"
android:windowSoftInputMode="adjustPan" />
<activity
android:name=".activity.MainActivity"
android:label="#string/app_name"
android:launchMode="singleTop" />
<activity
android:name=".activity.test"
android:label="#string/app_name"
android:launchMode="singleTop" />
<activity
android:name=".activity.SearchActivity"
android:label="MY SICK APP"
android:launchMode="singleTop" />
<activity
android:name=".activity.ImageActivity"
android:label="MY SICK APP"
android:launchMode="singleTop"
android:largeHeap="true"/>
</application>
</manifest>
-
public class ImageActivity extends Activity{
final String URL = "linktophpfile";
private Button button;
private String coded_string, name;
private Bitmap bitmap;
private File file;
private Uri uri;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_main);
button = (Button) findViewById(R.id.bt_main);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View view){
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
getUri();
i.putExtra(MediaStore.EXTRA_OUTPUT,uri);
startActivityForResult(i,5);
}
});
}
public void getUri() {
String name = "test123.jpeg";
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+ file.separator + name);
uri = Uri.fromFile(file);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==5 && resultCode== RESULT_OK){
new Encode_image().execute();
}
}
private class Encode_image extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... voids) {
bitmap = BitmapFactory.decodeFile(uri.getPath());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
bitmap.recycle();
byte[] array = stream.toByteArray();
coded_string = Base64.encodeToString(array,0);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
makeRequest();
}
}
private void makeRequest() {
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.POST,URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error){
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError{
HashMap<String, String> map = new HashMap<>();
map.put("coded_String", coded_string);
map.put("image_name", name);
return map;
}
};
queue.add(request);
}
}
php code:
<?php
header('Content-type : bitmap; charset=utf-8');
if(isset($_POST["encoded_string"])){
$encoded_string = $_POST["encoded_string"];
$image_name = $_POST["image_name"];
$decoded_string = base64_decode($encoded_string);
$path = 'images/'.$image_name;
$file = fopen($path, 'wb');
$is_written = fwrite($file, $decoded_string);
fclose($file);
if($is_written > 0) {
$connection = mysqli_connect('localhost', 'username', 'password','dbname');
$query = "INSERT INTO images(name,path) values('$image_name','$path');";
$result = mysqli_query($connection, $query) ;
if($result){
echo "success";
}else{
echo "failed";
}
mysqli_close($connection);
}
}
?>
Any ideas of what could be wrong? thanks
Make sure you have
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Declared in your manifest.xml file
1 check your app's permission states in phone settings.
2 Check this photo's real uri in debug mode.
Related
I tried to share an image loaded into the imageview from glide following this guide, it gives me a null pointer exception. I've posted the code and stacktrace below, it
MainActivity.java
public class MainActivity extends AppCompatActivity {
private EditText editText;
private ShareActionProvider myShareActionProvider;
//private Bitmap bitmap;
private Uri uri;
private Intent shareIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView imageView = (ImageView) findViewById(R.id.imageView);
String hi = "http://37n98a43dqtb4bua9n28nidp.wpengine.netdna-cdn.com/wp-content/uploads/2016/09/MyFriendPikachu.jpg";
Glide
.with(this)
.load(hi)
.listener(new RequestListener<String, GlideDrawable>() {
#Override
public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
return false;
}
#Override
public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
prepareShareIntent(((GlideBitmapDrawable) resource).getBitmap());
attachShareIntentAction();
return false;
}
})
.placeholder(R.drawable.ic_action_name)
.error(R.drawable.ic_img_error)
.centerCrop()
.into(imageView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.img_menu, menu);
MenuItem item = menu.findItem(R.id.action_share);
myShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(item);
attachShareIntentAction();
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
public void prepareShareIntent(Bitmap drawableImage) {
Uri bmpUri = getBitmapFromDrawable(drawableImage);
shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/*");
}
public void attachShareIntentAction() {
if (myShareActionProvider != null && shareIntent != null)
myShareActionProvider.setShareIntent(shareIntent);
}
public Uri getBitmapFromDrawable(Bitmap bmp) {
Uri bmpUri = null;
try {
File file = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "images" + System.currentTimeMillis() + ".png");
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = FileProvider.getUriForFile(MainActivity.this, "com.example.imnobody.sampleprojectnetwork", file); // use this version for API >= 24
// **Note:** For API < 24, you may use bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
}
fileprovider.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-file-path
name="images"
path="Pictures" />
</paths>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.imnobody.sampleprojectnetwork">
<uses-permission android:name="android.permission.INTERNET" />
<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">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.imnobody.sampleprojectnetwork.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/fileprovider" />
</provider>
</application>
</manifest>
Stacktrace
java.lang.NullPointerException
at android.support.v4.content.FileProvider.parsePathStrategy(FileProvider.java:583)
at android.support.v4.content.FileProvider.getPathStrategy(FileProvider.java:557)
at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:399)
at com.example.imnobody.sampleprojectnetwork.MainActivity.getBitmapFromDrawable(MainActivity.java:134)
at com.example.imnobody.sampleprojectnetwork.MainActivity.prepareShareIntent(MainActivity.java:95)
at com.example.imnobody.sampleprojectnetwork.MainActivity$1.onResourceReady(MainActivity.java:59)
at com.example.imnobody.sampleprojectnetwork.MainActivity$1.onResourceReady(MainActivity.java:51)
at com.bumptech.glide.request.GenericRequest.onResourceReady(GenericRequest.java:522)
at com.bumptech.glide.request.GenericRequest.onResourceReady(GenericRequest.java:507)
at com.bumptech.glide.load.engine.EngineJob.handleResultOnMainThread(EngineJob.java:158)
at com.bumptech.glide.load.engine.EngineJob.access$100(EngineJob.java:22)
at com.bumptech.glide.load.engine.EngineJob$MainThreadCallback.handleMessage(EngineJob.java:202)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
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:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Your <provider> has the following android:authorities value:
com.example.imnobody.sampleprojectnetwork.fileprovider
This is what you are providing to getUriForFile(), claiming that it is your provider's authority:
com.example.imnobody.sampleprojectnetwork
These are not the same, and they need to be.
I have an Android app that posts to "http://jont.byethost3.com/gcmtest/gcm.php?shareRegId=true". Once that is accessed, the app posts an id key to the script and the php file saves it to a textfile on my file server.
I have manually entered the url into my browser and it successfully generated an empty text file due to not receiving any POST data but when I test it on my app, it doesn't work.
I use Asynchttp to call and pass the data like this
private void backgroundRegister(final String username){
new AsyncTask<Void, Void, String>(){
#Override
protected String doInBackground(Void... params) {
String msg = "";
try{
if(gcmObj==null){
gcmObj = GoogleCloudMessaging.getInstance(getApplicationContext());
}
registerID = gcmObj.register(AppConstants.PROJ_ID);
msg = "Registration ID : " + registerID;
Log.d("REGOID",registerID);
}catch(IOException e){
Log.d("IOEXCEPTION",e.toString());
}
return msg;
}
#Override
protected void onPostExecute(String s) {
if(!TextUtils.isEmpty(registerID)){
savetoSharedPrefs(getApplicationContext(),registerID,username);
Toast.makeText(getApplicationContext(),"Registered with GCM",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(),"Registration failed",Toast.LENGTH_LONG).show();
}
}
}.execute(null, null, null);
}
private void savetoSharedPrefs(Context context, String registerID,String userName){
SharedPreferences prefs = getSharedPreferences("userDetails", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(regID, registerID);
editor.putString(userNAME, userName);
editor.commit();
storeREG();
}
//store in the file server (PHP)
private void storeREG(){
pg.show();
params.put("regID", registerID);
//Make RESTful webservice call
AsyncHttpClient client = new AsyncHttpClient();
client.post(AppConstants.SERVER_URL,params,new AsyncHttpResponseHandler(){
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
pg.hide();
if(pg!=null){
pg.dismiss();
}
Toast.makeText(getApplicationContext(),"ID sharing successful",Toast.LENGTH_LONG).show();
Intent home = new Intent(getApplicationContext(),HomeActivity.class);
home.putExtra("regID",registerID);
Log.d("REGID",registerID);
startActivity(home);
finish();
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
pg.hide();
if(pg!=null){
pg.dismiss();
}
if(statusCode==404){
Toast.makeText(getApplicationContext(),"Requested resource not found",Toast.LENGTH_LONG).show();
}else if(statusCode==500){
Toast.makeText(getApplicationContext(),"Something went wrong at the server",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(),"Unexpected error occurred",Toast.LENGTH_LONG).show();
}
}
});
}
The data I want to pass is just plaintext.
I hope someone can help me with this.
EDIT
My php script
if(!empty($_GET["shareRegId"])) {
$gcmRegID = $_POST["regID"];
//echo $gcmRegID;
file_put_contents("./GCMRegId.txt",$gcmRegID);
echo "Done!";
exit;
}
My manifest just in case
<?xml version="1.0" encoding="utf-8"?>
<!-- GCM Permissions - Start here -->
<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.amosang.pushtest.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.amosang.pushtest.permission.C2D_MESSAGE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE" />
<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>
<activity
android:name=".HomeActivity"
android:label="#string/title_activity_home" >
</activity>
<receiver
android:name=".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" />
<action android:name="com.example.amosang.pushtest" />
</intent-filter>
</receiver>
<service android:name=".GCMNotificationIntentService" />
</application>
UPDATE :
I have managed to get this code working locally using my mamp server, the issue remains when i upload it to this host.
In order to pass Post params using AsyncAndroidHttp library you can use the provided RequestParams class and pass that to your Post API call, a little demonstration of what i mean :
AsyncHttpClient client = new AsyncHttpClient();
RequestParams req = new RequestParams();
req.add("shareRegId","true");
client.post(AppConstants.SERVER_URL,req,new AsyncHttpResponseHandler(){
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
pg.hide();
if(pg!=null){
pg.dismiss();
}
Toast.makeText(getApplicationContext(),"ID sharing successful",Toast.LENGTH_LONG).show();
Intent home = new Intent(getApplicationContext(),HomeActivity.class);
home.putExtra("regID",registerID);
Log.d("REGID",registerID);
startActivity(home);
finish();
}
This will help you pass Post Params,
I want get the install referrer value in my MainActivity. For that i am using two class
1) MainActivity
2) ReferrerReceiver
I got received install referrer value successfully in ReferrerReceiver class, i tested this using Toast control.
But i can not able to pass this value to MainActivity from ReferrerReceiver.
Bellow is i tried code. please any one help me.
Thanks for advance.
1) MainActivity.java
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv1 = (TextView) findViewById(R.id.tv1);
Intent in1= getIntent();
String ldString = in1.getStringExtra("number");
tv1.setText(ldString);
}
}
2) ReferrerReceiver.java
public class ReferrerReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (!intent.getAction().equals("com.android.vending.INSTALL_REFERRER")) {
return;
}
Bundle bundle = intent.getExtras();
String phoneNumber = bundle.getString("referrer");
Intent i = new Intent(context, MainActivity.class);
i.putExtra("number", phoneNumber);
context.startActivity(i);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.myreferrer.in"
android:versionCode="7"
android:versionName="1.0.6" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
>
<receiver android:name="com.myreferrer.in.ReferrerReceiver"
android:enabled="true">
<action android:name="com.android.vending.INSTALL_REFERRER" />
</intent-filter>
</receiver>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:launchMode="singleTask"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
This was i implemented in my project. its working for me. Use this code
(1) MainActivity.java
public class MainActivity extends Activity {
TextView tv1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(R.id.tv1);
}
public static void log(Context context, String string) {
if(string!=null) {
Toast.makeText(conte, "Referrer value is."+string, Toast.LENGTH_LONG).show();
tv1.setText(string);
}
}
(2) ReferrerReceiver.java
public class ReferrerReceiver extends BroadcastReceiver {
String referrer,rawReferrer;
public static String getReferrer(Context context) {
// Return any persisted referrer value or null if we don't have a referrer.
return context.getSharedPreferences("referrer", Context.MODE_PRIVATE).getString("referrer", null);
}
#Override
public void onReceive(Context context, Intent intent) {
try {
// Make sure this is the intent we expect - it always should be.
if ((null != intent) && (intent.getAction().equals("com.android.vending.INSTALL_REFERRER"))) {
// This intent should have a referrer string attached to it.
rawReferrer = intent.getStringExtra("referrer");
if (null != rawReferrer) {
// The string is usually URL Encoded, so we need to decode it.
referrer = URLDecoder.decode(rawReferrer, "UTF-8");
Toast.makeText(context, "ReferrerReceiver." + referrer, Toast.LENGTH_LONG).show();
MainActivity.log(context,"\nRaw referrer: " + rawReferrer +"\nReferrer: " + referrer);
MainActivity.log(context,referrer);
// Persist the referrer string.
context.getSharedPreferences("referrer", Context.MODE_PRIVATE).
edit().putString("referrer", referrer).commit();
} else {
Toast.makeText(context, "ReferrerReceiver." + referrer, Toast.LENGTH_LONG).show();
MainActivity.log(context,referrer);
context.getSharedPreferences("referrer", Context.MODE_PRIVATE).
edit().putString("referrer", referrer).commit();
}
} else {
Toast.makeText(context, "ReferrerReceiver intent value is null.", Toast.LENGTH_LONG).show();
MainActivity.log(context,referrer);
MainActivity.log(context,"intent value is nulll");
context.getSharedPreferences("referrer", Context.MODE_PRIVATE).
edit().putString("referrer", "intent value is nulll").commit();
}
}
catch (Exception e) {
//Toast.makeText(context, "ReferrerReceiver catch"+e, Toast.LENGTH_LONG).show();
MainActivity.log(context, e.toString());
}
}
}
(3) AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.myreferrer.in"
android:versionCode="7"
android:versionName="1.0.6" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
>
<receiver android:name="com.myreferrer.ReferrerReceiver" android:exported="true">
<intent-filter>
<action android:name="com.android.vending.INSTALL_REFERRER"></action>
</intent-filter>
</receiver>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:launchMode="singleTask"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
(4) sample link:
https://play.google.com/store/apps/details?id=your_package_name&referrer=Welcome
You are using
Intent in1 = new Intent();
String ldString = in1.getStringExtra("KEY");
you are declaring new intent which is wrong, and also key you put is also wrong, which should be number
Replace it With,
Intent intent= getIntent();
String ldString = intent.getStringExtra("number");
you have declared your activity as"single Task" in Manifest;so if an instance of your
activity is already launched the system will create (NewIntent) to re_lunch your
activity.try to put this code before onCreate():
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// NOW getIntent() should always return the recent
setIntent(intent);
}
to get all the time the newest intent with the new extras.
I try to share a post on google+ but I obtain this Exception. The Activity that creates the Exception is ExampleActivity and this is its code:
public class ExampleActivity extends Activity implements OnClickListener,
ConnectionCallbacks, OnConnectionFailedListener {
private static final String TAG = "ExampleActivity";
private static final int REQUEST_CODE_RESOLVE_ERR = 9000;
private ProgressDialog mConnectionProgressDialog;
private PlusClient mPlusClient;
private ConnectionResult mConnectionResult;
#Override//onCreate
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_example);
mPlusClient = new PlusClient.Builder(this, this, this)
.setVisibleActivities("http://schemas.google.com/AddActivity","http://schemas.google.com/BuyActivity")
.build();
// Progress bar to be displayed if the connection failure is not resolved.
mConnectionProgressDialog = new ProgressDialog(this);
mConnectionProgressDialog.setMessage("Signing in...");
Button shareButton = (Button) findViewById(R.id.share_button);
shareButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Launch the Google+ share dialog with attribution to your app.
Intent shareIntent = new PlusShare.Builder()
.setType("text/plain")
.setText("Welcome to
the Google+ platform.")
.setContentUrl(Uri.parse("https://developers.google.com/+/"))
.getIntent();
startActivityForResult(shareIntent, 0);
}
});
}
#Override//onStart
protected void onStart() {
super.onStart();
mPlusClient.connect();
}
#Override//onStop
protected void onStop() {
super.onStop();
mPlusClient.disconnect();
}
#Override// onConnectionFailed
public void onConnectionFailed(ConnectionResult result) {
if (mConnectionProgressDialog.isShowing()) {
// The user clicked the sign-in button already. Start to resolve
// connection errors. Wait until onConnected() to dismiss the
// connection dialog.
if (result.hasResolution()) {
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLVE_ERR);
} catch (SendIntentException e) {
mPlusClient.connect();
}
}
}
// Save the result and resolve the connection failure upon a user click.
mConnectionResult = result;
}
#Override //onActivityResult
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
if (requestCode == REQUEST_CODE_RESOLVE_ERR && responseCode == RESULT_OK) {
mConnectionResult = null;
mPlusClient.connect();
}
}
// #Override
// public void onConnected(Bundle connectionHint) {
// String accountName = mPlusClient.getAccountName();
// Toast.makeText(this, accountName + " is connected.", Toast.LENGTH_LONG).show();
// }
#Override //onDisconnected
public void onDisconnected() {
String accountName = mPlusClient.getAccountName();
Toast.makeText(this, accountName + " is connected.", Toast.LENGTH_LONG).show();
}
#Override//onConnected
public void onConnected() {
// TODO Auto-generated method stub
}
#Override
public void onClick(View arg0) {
}
}
This is the AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.applicazionescienza"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.applicazionescienza.Menu"
android:label="#string/app_name"
android:launchMode="singleInstance" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.applicazionescienza.Informazioni"
android:label="#string/title_activity_informazioni" >
</activity>
<activity
android:name="com.example.applicazionescienza.Regolamento"
android:label="#string/title_activity_regolamento" >
</activity>
<activity
android:name="com.example.applicazionescienza.Gioca"
android:label="#string/title_activity_gioca" >
</activity>
<activity
android:name="com.example.applicazionescienza.Livello"
android:label="#string/title_activity_livello" >
</activity>
<activity
android:name="com.example.applicazionescienza.Punteggio"
android:label="#string/title_activity_punteggio" >
</activity>
<activity
android:name="com.example.applicazionescienza.TwitterActivity"
android:label="#string/title_activity_twitter"
android:launchMode="singleInstance" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="casa"
android:scheme="app" />
</intent-filter>
</activity>
<activity
android:name="com.example.applicazionescienza.FacebookActivity"
android:label="#string/title_activity_facebook" >
</activity>
<activity
android:name="com.example.applicazionescienza.ExampleActivity"
android:label="#string/title_activity_example" >
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
The Exception say: No activity found to handle Intent(act=android.intent.action.SEND....
Someone can help me?
Try and clean the project, uninstall your app from device and reinstall.
The problem is that if i use these two lines of code,my app closes unxepectedly and if not used, the app works just fine...is there any other way to get to the maps.class?
The following is the code i used:
Intent in = new Intent(BlobCity.this, maps.class)
startActivity(in);
the following is my manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="BlobCity.xyz.com"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-library android:name="com.google.android.maps" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".BlobCity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".maps" />
</application>
</manifest>
blobcity.java:
public class BlobCity extends Activity
{
/** Called when the activity is first created. */
Button signIn,register;
TextView Blob,City,username,password;
EditText eUsername,ePassword;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
signIn = (Button) findViewById(R.id.signIn);
register = (Button) findViewById(R.id.register);
Blob = (TextView) findViewById(R.id.blob);
City = (TextView) findViewById(R.id.city);
username = (TextView) findViewById(R.id.username);
password = (TextView) findViewById(R.id.password);
eUsername = (EditText) findViewById(R.id.eUsername);
ePassword = (EditText) findViewById(R.id.ePassword);
signIn.setOnClickListener(new sendUserPass());
register.setOnClickListener(new regPage());
}
class sendUserPass implements Button.OnClickListener
{
public void onClick(View v)
{
String uname = eUsername.getText().toString();
String pwd = ePassword.getText().toString();
String requestString = ("http://192.168.1.102:8080/BlobCity/RemoteLogin?email="+ uname + "&pwd=" + pwd);
String line;
try {
HttpResponse response = new DefaultHttpClient().execute(new HttpGet(requestString));
InputStream is = response.getEntity().getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder rb = new StringBuilder("");
while ((line=br.readLine()) != null)
{
rb.append(line) ;
}
if(rb.toString().equals("0"))
{
Toast toast = Toast.makeText(getApplicationContext(), "Please enter a valid Username and/or Password!", Toast.LENGTH_LONG);
toast.show();
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
eUsername.setText("");
ePassword.setText("");
}
else
{
Intent in = new Intent(BlobCity.this, maps.class);
startActivity(in);
eUsername.setText("");
ePassword.setText("");
}
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
class regPage implements Button.OnClickListener
{
public void onClick(View v)
{
Intent browse = new Intent( Intent.ACTION_VIEW , Uri.parse("http://www.blobcity.com") );
startActivity(browse);
}
}
}
maps.java:
import android.os.Bundle;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
public class maps extends MapActivity{
MapView mapView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
mapView = (MapView) findViewById(R.id.map);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
Your tag <uses-library android:name="com.google.android.maps" /> has to be inside the <application> tag!
manifest has to be like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="BlobCity.xyz.com"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application android:icon="#drawable/icon" android:label="#string/app_name">
**<uses-library android:name="com.google.android.maps" />**
<activity android:name=".BlobCity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".maps" />
</application>
</manifest>
Try:
Intent in = new Intent(BlobCity.this.getApplicationContext(), maps.class)
startActivity(in);
Activity (Class) name must start with capital letter, and instead of using BlobCity.this use only "this" keyword which refers the Context of the current Activity
e.g.
Intent in = new Intent(this, Maps.class)
startActivity(in);
also make sure entry of this Activity must be in your AndroidManifest.xml file
e.g.
<activity android:name=".Maps"></activity>
also you can follow a great tutorial on Android Google Maps here :
http://mobiforge.com/developing/story/using-google-maps-android