[GUIDE] Working with Parse | Push notifications | Users | Saving data | More - Java for Android App Development

Hey guys!
I know most of you have never heard of this, but there's a organisation that provides many useful things to use in your app!
It's called "Parse"
Now, I will guide you trough the use of Parse, beginning with Parse Push. Let's get started, shall we?
Section 1:
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Okay, so Parse Push is a "library" or service that makes it A LOT easier to send push notifications to the users of your app. I had searched for months on how to send push notifications, but I just never succeeded (And I can't afford a proper server ). But that's where Parse Push comes in!
The first thing you'll have to do to setup Parse Push is download and install the Parse SDK. This is how:
Step 1: Make an account at Parse.com and setup the app you want to include Parse in.
Step 2: Download the SDK: https://parse.com/downloads/android/Parse/latest
Step 3: Unzip it into a random folder
Step 4: Copy all the files in your projects "lib" folder. If your project doesn't have one, simply make one in the root of your directory (e.g /MyApp/lib/)
Step 5: Call the "initialize" method in your onCreate method, like this:
Code:
Parse.initialize(this, "Your application ID", "Your client key");
NOTE: You can find you application ID and client key here: https://parse.com/apps/YOUR-APP'S-NAME/edit#app_keys
NOTE: Be sure you also imported these calls:
Code:
import com.parse.Parse;
import com.parse.ParseAnalytics;
Step 6: Your app needs the android.permission.INTERNET and android.permission.ACCESS_NETWORK_STATE permission to work with Parse, so add these lines in your AndroidManifest.xml file, right before the <application> tag:
Code:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Also, add this between the <application> and </application> tag:
Code:
<service android:name="com.parse.PushService" />
<receiver android:name="com.parse.ParseBroadcastReceiver">
Step 7: Place this code in your onCreate method to track how many times your app has been opened:
Code:
ParseAnalytics.trackAppOpened(getIntent());
Step 8: It's testing time!
To test if your app has been setup the right way, add this code to your onCreate method:
Code:
ParseObject object = new ParseObject("TestObject");
object.put("name", "testname");
object.saveInBackground();
And run your app!
Step 9: Get your data trough a web browser! Go to this site: https://parse.com/apps/YOUR-APP'S-NAME/collections
Then it should say something like: TestObject (1), with the name testname
Step 10: Send a push notification: Goto https://parse.com/apps/YOUR-APP'S-NAME/push_notifications and click on + Send a push
Type in your message, hit Send notification at the bottom and your app will get a push notification!
That's it! You have now setup your app to receive push notifications

Okay, here we go, the next section
Section 2: Parse Users
So, the ParseUser class is a really useful thingy for people who want to have some more control over the people who use their apps.
You can (for example) set a username, and then when the user wants to post something in the app, instead of him having to type his name all over again, the app can just use the ParseUser.getCurrentUser().getUsername() method, and it will automatigally get the user's name for him!
Now I'll show you how to setup a ParseUser:
Step 1: Setup everything in the same way as you did in Section 1
Step 2: First we'll have to make a ParseUser, by signing up. Here's a quick signing up code snippet:
Code:
ParseUser signup = new ParseUser();
signup.setUsername("testuser");
signup.setPassword("testpassword");
signup.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
// Hooray! Let them use the app now.
// The user also is logged in now :)
} else {
// Sign up didn't succeed. Look at the ParseException
// to figure out what went wrong
// Mostly the problem is that the username is already taken
}
But, ofcourse the user wants to choose his own username and password. For that you can use an EditText:
Code:
EditText username = (EditText) findViewById(R.id.USERNAMEEDITTEXTiD);
EditText password = (EditText) findViewById(R.id.PASSWORDEDITTEXTiD);
ParseUser signup = new ParseUser();
signup.setUsername(username.getText().toString());
signup.setPassword(password.getText().toString());
signup.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
// Hooray! Let them use the app now.
// The user also is logged in now :)
} else {
// Sign up didn't succeed. Look at the ParseException
// to figure out what went wrong
// Mostly the problem is that the username is already taken
}
But, if the user didn't type in anything, signin up throws a IllegalArgumentException. You can avoid that by using try and catch claws, like in this example:
Code:
EditText username = (EditText) findViewById(R.id.USERNAMEEDITTEXTiD);
EditText password = (EditText) findViewById(R.id.PASSWORDEDITTEXTiD);
try {
ParseUser signup = new ParseUser();
signup.setUsername(username.getText().toString());
signup.setPassword(password.getText().toString());
signup.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
// Hooray! Let them use the app now.
// The user also is logged in now :)
} else {
// Sign up didn't succeed. Look at the ParseException
// to figure out what went wrong
// Mostly the problem is that the username is already taken
}
} catch (IllegalArgumentException IO {
// The user didn't type in anything, I suggest using a Toast to notify him
}
Now, if a user wants to post something using his account name, you can get his username using this:
Code:
ParseUser currentUser = ParseUser.getCurrentUser();
currentUser.getUsername();
If your user wants to login, you can use this:
Code:
EditText username = (EditText) findViewById(R.id.USERNAMEEDITTEXT);
EditText password = (EditText) findViewById(R.id.PASSWORDEDITTEXT);
ParseUser.logInInBackground(username.getText().toString(), password .getText().toString(), new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
// Hooray! The user is logged in.
} else {
// Signup failed. Look at the ParseException to see what happened.
// The main cause is that the user didn't type in a correct username or password
}
}
});
And if you want to log the user out, you can do it very simply by calling:
Code:
ParseUser.logOut();
And that's it! You just learned how to signup a user, log him in, get his username and log him out!
Now it's time for the next section!

Time for section 3!
Section 3: Parse Data
Huh, what is Parse Data? Well, that's a good question sir! P) Parse Data will let you save ParseObjects into the Parse Cloud. That will allow you to store all of your data, and if you want you can read it back too! This could be useful for games with highscores, forum apps and more! Another great part of Parse!
Let's start with saving a ParseObject to the cloud, shall we?
Step 1: Setup your app the same way you did in Section 1
Step 2: We'll start with a really simple ParseObject, for now it's going to be called "testObject"
Here's a quick example for a ParseObject that will save to the cloud:
Code:
ParseObject testObject= new ParseObject("testObject");
testObject.put("name", "TestObject's name");
testObject.put("random",true);
testObject.put("someint", 1337);
testObject.saveInBackground();
As you can see, we can put everything we want in it (e.g. testObject.put("ASDASDASDA", "ASDASDASD")
They don't always have to be strings, they can be booleans, ints, strings, JSON objects, java.util.Date, byte[] or ParseObjects(That's right, you can save a ParseObject inside a ParseObject )
You can also wait for the user untill he has an internet connection, and when he finally has, save the object:
Code:
ParseObject testObject= new ParseObject("testObject");
testObject.put("name", "TestObject's name");
testObject.put("random",true);
testObject.put("someint", 1337);
testObject.saveEventually();
For retreiving the object, you can do something like this:
Code:
ParseQuery<ParseObject> query = ParseQuery.getQuery("testObject");
query.getInBackground("YOUROBJECTID", new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (e == null) {
// everything went okay :D
} else {
// something went wrong D:
}
}
})
Updating a ParseObject is really simple, just use the same as you did before, but with new data in the testObject.put("somedata", "the data"); section
Deleting it is farely simple as well, just use this:
Code:
testObject.deleteInBackground();
You can also delete just one field:
Code:
testObject.remove("name");
testObject.saveInBackground();
And that's it for now!

And again, mine

Last one

This really is the last one!

Wow! Great. :good:
Thanks.
How much is the 1 GB per month which you get for free?
EDIT: Saw that this is the storage. You get 1,000,000 notifications for free.

nikwen said:
Wow! Great. :good:
Thanks.
How much is the 1 GB per month which you get for free?
Click to expand...
Click to collapse
Well it's really good, as 100 push notifications is just 0.1 % of the whole 1 GB
So, it's enough for me

MaartenXDA said:
Well it's really good, as 100 push notifications is just 0.1 % of the whole 1 GB
So, it's enough for me
Click to expand...
Click to collapse
10 kB per message? Sounds good. Thanks.

ParseUsers section updated!

Ok. Just saw that you get 1,000,000 messages for free.
That is great for small apps but if you go beyond that, it will be very expensive. However, I cannot compare it to the price of a server.
Any experiences?

nikwen said:
Ok. Just saw that you get 1,000,000 messages for free.
That is great for small apps but if you go beyond that, it will be very expensive. However, I cannot compare it to the price of a server.
Any experiences?
Click to expand...
Click to collapse
Yeah, well, the internet keeps getting more and more expensive. I don't like it either, but my app isn't that big so I can live with it
ParseData section updated!

Good job Maarten! So this is your method..! xD
Keep it up!
xpirt

help needed
Code:
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()){
case R.id.bgo2:
try{
username=et1.getText().toString();
password=et2.getText().toString();
ParseUser signup = new ParseUser();
signup.setUsername(username);
signup.setPassword(password);
signup.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
// Hooray! Let them use the app now.
Intent i = new Intent(MainActivity.this,Slider.class);
startActivity(i);
} else {
// Sign up didn't succeed. Look at the ParseException
// to figure out what went wrong
Toast.makeText(MainActivity.this, "something wrong" , Toast.LENGTH_SHORT).show();
}
}
});
} catch (IllegalArgumentException IO) {
// The user didn't type in anything, I suggest using a Toast to notify him
Toast.makeText(MainActivity.this, "Please type something" , Toast.LENGTH_SHORT).show();
}
this is my code for signup on click of a button. everything is setup. but nothing happens when i click on sighn up button. and when i click on sigh in.. the app exits with an error. logcat says:-
Code:
06-03 11:55:41.761: E/SpannableStringBuilder(15340): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
06-03 11:55:41.761: E/SpannableStringBuilder(15340): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
06-03 11:55:42.178: E/NativeCrypto(15340): ssl=0x52f7c578 cert_verify_callback x509_store_ctx=0x52112a80 arg=0x0
06-03 11:55:42.178: E/NativeCrypto(15340): ssl=0x52f7c578 cert_verify_callback calling verifyCertificateChain authMethod=RSA
06-03 11:55:50.001: E/AndroidRuntime(15340): FATAL EXCEPTION: main
06-03 11:55:50.001: E/AndroidRuntime(15340): java.lang.IllegalArgumentException: Must specify a username for the user to log in with
06-03 11:55:50.001: E/AndroidRuntime(15340): at com.parse.ParseUser.logInAsync(ParseUser.java:655)
06-03 11:55:50.001: E/AndroidRuntime(15340): at com.parse.ParseUser.logInInBackground(ParseUser.java:715)
06-03 11:55:50.001: E/AndroidRuntime(15340): at com.sandy.letsfixthat.MainActivity.onClick(MainActivity.java:98)
06-03 11:55:50.001: E/AndroidRuntime(15340): at android.view.View.performClick(View.java:4091)
06-03 11:55:50.001: E/AndroidRuntime(15340): at android.view.View$PerformClick.run(View.java:17072)
06-03 11:55:50.001: E/AndroidRuntime(15340): at android.os.Handler.handleCallback(Handler.java:615)
06-03 11:55:50.001: E/AndroidRuntime(15340): at android.os.Handler.dispatchMessage(Handler.java:92)
06-03 11:55:50.001: E/AndroidRuntime(15340): at android.os.Looper.loop(Looper.java:153)
06-03 11:55:50.001: E/AndroidRuntime(15340): at android.app.ActivityThread.main(ActivityThread.java:5086)
06-03 11:55:50.001: E/AndroidRuntime(15340): at java.lang.reflect.Method.invokeNative(Native Method)
06-03 11:55:50.001: E/AndroidRuntime(15340): at java.lang.reflect.Method.invoke(Method.java:511)
06-03 11:55:50.001: E/AndroidRuntime(15340): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
06-03 11:55:50.001: E/AndroidRuntime(15340): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
06-03 11:55:50.001: E/AndroidRuntime(15340): at dalvik.system.NativeStart.main(Native Method)
06-03 11:55:56.435: E/Trace(15377): error opening trace file: No such file or directory (2)
06-03 11:55:56.452: E/com.parse.PushService(15377): The Parse push service cannot start because Parse.initialize has not yet been called.
If you call Parse.initialize from an Activity's onCreate, that call should instead be in the Application.onCreate.
Be sure your Application class is registered in your AndroidManifest.xml with the android:name property of your <application> tag.
push notification working fine for me.

Sandy||Striker said:
Code:
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()){
case R.id.bgo2:
try{
username=et1.getText().toString();
password=et2.getText().toString();
ParseUser signup = new ParseUser();
signup.setUsername(username);
signup.setPassword(password);
signup.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
// Hooray! Let them use the app now.
Intent i = new Intent(MainActivity.this,Slider.class);
startActivity(i);
} else {
// Sign up didn't succeed. Look at the ParseException
// to figure out what went wrong
Toast.makeText(MainActivity.this, "something wrong" , Toast.LENGTH_SHORT).show();
}
}
});
} catch (IllegalArgumentException IO) {
// The user didn't type in anything, I suggest using a Toast to notify him
Toast.makeText(MainActivity.this, "Please type something" , Toast.LENGTH_SHORT).show();
}
this is my code for signup on click of a button. everything is setup. but nothing happens when i click on sighn up button. and when i click on sigh in.. the app exits with an error. logcat says:-
Code:
06-03 11:55:41.761: E/SpannableStringBuilder(15340): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
06-03 11:55:41.761: E/SpannableStringBuilder(15340): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
06-03 11:55:42.178: E/NativeCrypto(15340): ssl=0x52f7c578 cert_verify_callback x509_store_ctx=0x52112a80 arg=0x0
06-03 11:55:42.178: E/NativeCrypto(15340): ssl=0x52f7c578 cert_verify_callback calling verifyCertificateChain authMethod=RSA
06-03 11:55:50.001: E/AndroidRuntime(15340): FATAL EXCEPTION: main
06-03 11:55:50.001: E/AndroidRuntime(15340): java.lang.IllegalArgumentException: Must specify a username for the user to log in with
06-03 11:55:50.001: E/AndroidRuntime(15340): at com.parse.ParseUser.logInAsync(ParseUser.java:655)
06-03 11:55:50.001: E/AndroidRuntime(15340): at com.parse.ParseUser.logInInBackground(ParseUser.java:715)
06-03 11:55:50.001: E/AndroidRuntime(15340): at com.sandy.letsfixthat.MainActivity.onClick(MainActivity.java:98)
06-03 11:55:50.001: E/AndroidRuntime(15340): at android.view.View.performClick(View.java:4091)
06-03 11:55:50.001: E/AndroidRuntime(15340): at android.view.View$PerformClick.run(View.java:17072)
06-03 11:55:50.001: E/AndroidRuntime(15340): at android.os.Handler.handleCallback(Handler.java:615)
06-03 11:55:50.001: E/AndroidRuntime(15340): at android.os.Handler.dispatchMessage(Handler.java:92)
06-03 11:55:50.001: E/AndroidRuntime(15340): at android.os.Looper.loop(Looper.java:153)
06-03 11:55:50.001: E/AndroidRuntime(15340): at android.app.ActivityThread.main(ActivityThread.java:5086)
06-03 11:55:50.001: E/AndroidRuntime(15340): at java.lang.reflect.Method.invokeNative(Native Method)
06-03 11:55:50.001: E/AndroidRuntime(15340): at java.lang.reflect.Method.invoke(Method.java:511)
06-03 11:55:50.001: E/AndroidRuntime(15340): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
06-03 11:55:50.001: E/AndroidRuntime(15340): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
06-03 11:55:50.001: E/AndroidRuntime(15340): at dalvik.system.NativeStart.main(Native Method)
06-03 11:55:56.435: E/Trace(15377): error opening trace file: No such file or directory (2)
06-03 11:55:56.452: E/com.parse.PushService(15377): The Parse push service cannot start because Parse.initialize has not yet been called.
If you call Parse.initialize from an Activity's onCreate, that call should instead be in the Application.onCreate.
Be sure your Application class is registered in your AndroidManifest.xml with the android:name property of your <application> tag.
push notification working fine for me.
Click to expand...
Click to collapse
I think that the EditText for the username is empty.
Quote from second post:
But, if the user didn't type in anything, signin up throws a IllegalArgumentException.
Click to expand...
Click to collapse

nikwen said:
I think that the EditText for the username is empty.
Quote from second post:
Click to expand...
Click to collapse
no its not empty.. i tried with a few entries.. it is not signing up users??
the above code is for signing the new users

Sandy||Striker said:
no its not empty.. i tried with a few entries.. it is not signing up users??
the above code is for signing the new users
Click to expand...
Click to collapse
Just checked the logs again. They contain instructions to get it working:
The Parse push service cannot start because Parse.initialize has not yet been called.
If you call Parse.initialize from an Activity's onCreate, that call should instead be in the Application.onCreate.
Be sure your Application class is registered in your AndroidManifest.xml with the android:name property of your <application> tag.
Click to expand...
Click to collapse

@nikwen
this is the error now
i am getting this on clicking signup button
Code:
06-03 12:12:51.893: E/SpannableStringBuilder(22529): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
06-03 12:12:51.893: E/SpannableStringBuilder(22529): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
06-03 12:12:59.150: E/AndroidRuntime(22529): FATAL EXCEPTION: main
06-03 12:12:59.150: E/AndroidRuntime(22529): java.lang.NullPointerException
06-03 12:12:59.150: E/AndroidRuntime(22529): at com.sandy.letsfixthat.MainActivity.onClick(MainActivity.java:55)
06-03 12:12:59.150: E/AndroidRuntime(22529): at android.view.View.performClick(View.java:4091)
06-03 12:12:59.150: E/AndroidRuntime(22529): at android.view.View$PerformClick.run(View.java:17072)
06-03 12:12:59.150: E/AndroidRuntime(22529): at android.os.Handler.handleCallback(Handler.java:615)
06-03 12:12:59.150: E/AndroidRuntime(22529): at android.os.Handler.dispatchMessage(Handler.java:92)
06-03 12:12:59.150: E/AndroidRuntime(22529): at android.os.Looper.loop(Looper.java:153)
06-03 12:12:59.150: E/AndroidRuntime(22529): at android.app.ActivityThread.main(ActivityThread.java:5086)
06-03 12:12:59.150: E/AndroidRuntime(22529): at java.lang.reflect.Method.invokeNative(Native Method)
06-03 12:12:59.150: E/AndroidRuntime(22529): at java.lang.reflect.Method.invoke(Method.java:511)
06-03 12:12:59.150: E/AndroidRuntime(22529): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
06-03 12:12:59.150: E/AndroidRuntime(22529): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
06-03 12:12:59.150: E/AndroidRuntime(22529): at dalvik.system.NativeStart.main(Native Method)

Sandy||Striker said:
@nikwen
this is the error now
i am getting this on clicking signup button
Code:
06-03 12:12:51.893: E/SpannableStringBuilder(22529): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
06-03 12:12:51.893: E/SpannableStringBuilder(22529): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
06-03 12:12:59.150: E/AndroidRuntime(22529): FATAL EXCEPTION: main
06-03 12:12:59.150: E/AndroidRuntime(22529): java.lang.NullPointerException
06-03 12:12:59.150: E/AndroidRuntime(22529): at com.sandy.letsfixthat.MainActivity.onClick(MainActivity.java:55)
06-03 12:12:59.150: E/AndroidRuntime(22529): at android.view.View.performClick(View.java:4091)
06-03 12:12:59.150: E/AndroidRuntime(22529): at android.view.View$PerformClick.run(View.java:17072)
06-03 12:12:59.150: E/AndroidRuntime(22529): at android.os.Handler.handleCallback(Handler.java:615)
06-03 12:12:59.150: E/AndroidRuntime(22529): at android.os.Handler.dispatchMessage(Handler.java:92)
06-03 12:12:59.150: E/AndroidRuntime(22529): at android.os.Looper.loop(Looper.java:153)
06-03 12:12:59.150: E/AndroidRuntime(22529): at android.app.ActivityThread.main(ActivityThread.java:5086)
06-03 12:12:59.150: E/AndroidRuntime(22529): at java.lang.reflect.Method.invokeNative(Native Method)
06-03 12:12:59.150: E/AndroidRuntime(22529): at java.lang.reflect.Method.invoke(Method.java:511)
06-03 12:12:59.150: E/AndroidRuntime(22529): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
06-03 12:12:59.150: E/AndroidRuntime(22529): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
06-03 12:12:59.150: E/AndroidRuntime(22529): at dalvik.system.NativeStart.main(Native Method)
Click to expand...
Click to collapse
The error is in line 55 in MainActivity.java.
Could you please highlight this line?

nikwen said:
The error is in line 55 in MainActivity.java.
Could you please highlight this line?
Click to expand...
Click to collapse
Code:
password=et2.getText().toString();
---------- Post added at 12:58 PM ---------- Previous post was at 12:45 PM ----------
got the error.. thanks for your help

Related

[CODE][Q] Pass extra twice(image to mms), or use lastIndexOf() to get file?

Ok so this may get sort of complicated, but I'll try to explain it simply.
I have a mainActivity(viewpager). i take a screenshot of this from ABS options menu. This gets saved to sdcard . WORKS FINE
Code:
this is selecting from the actionbar menu
else if (item.getTitle().toString().equalsIgnoreCase("Take Screengrab")) {
View v1 = R1.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
Util.saveBitmap(bm, "folder", "screenshot");
//the above are the folder I chose to name, and the screenshotname{without additional numbering}
BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
image = (ImageView) findViewById(R.id.image4);
//imageview is above. second ativity is below
Intent intent = new Intent(this, Screenshots.class);
intent.putExtra("image", bm);
//"image" is my extra
startActivity(intent);
I send that while its saving, to an ImageView in a second(normal) activity. WORKS FINE
Code:
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screenshots);
//The ImageView where the screenshot goes
ImageView image=(ImageView)findViewById(R.id.image4);
//This "imageId" isnt used, but for some reason the Imageview wont set without it
Intent intent = getIntent();
int imageId = intent.getIntExtra("imageId", -1); // -1 would be a default value//
//this gets my extra
Bitmap bm = (Bitmap)this.getIntent().getParcelableExtra("image");
image.setImageBitmap(bm);
I have a button to share it, it opens with picture attached. SORT OF WORKING
The thing is, I want to automatically pass this same extra Bitmap and attach it to the message.
i can open a message with a known file attached.
Code:
{
Uri smsUri = Uri.parse("tel:0000000");
Intent intent = new Intent(Intent.ACTION_SEND, smsUri);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/folder/screenshot.png"));
intent.putExtra(Intent.EXTRA_TEXT,"Today");
startActivity(intent);
i tried the working in putExtra to the message, but I get a toast from the messaging app "Sorry, cannot attach this image". NO STACK ERRORS. nothign in the logs I can use.
Code:
Uri smsUri = Uri.parse("tel:0000000");
Intent intent = new Intent(Intent.ACTION_SEND, smsUri);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("image"));
intent.putExtra(Intent.EXTRA_TEXT,"Today");
startActivity(intent);
and other stuff like that that.
I currently am loading a known file into the message and it works perfect. Problem is, I wont know the name of the file, because my screenshots get saved as image1, image2, etc. So it will be different in every case.
So im wondering if its even possible to pass and extra through twice like that, or if I should look into return the latest image in that sdcard folder with like lastIndexOf(), or something similar.
basically, is there a way to simply query find and attach the highest numbered file? without a GUI(i can do select from gallery, but am trying to make it more automated).
any thoughts would be appreciated.
P.S. i know about the lint errors and things, and somewhat sloppy self taught java, but its working. only worried about the image passing.
out of ideas said:
Ok so this may get sort of complicated, but I'll try to explain it simply.
I have a mainActivity(viewpager). i take a screenshot of this from ABS options menu. This gets saved to sdcard . WORKS FINE
Code:
this is selecting from the actionbar menu
else if (item.getTitle().toString().equalsIgnoreCase("Take Screengrab")) {
View v1 = R1.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
Util.saveBitmap(bm, "folder", "screenshot");
//the above are the folder I chose to name, and the screenshotname{without additional numbering}
BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
image = (ImageView) findViewById(R.id.image4);
//imageview is above. second ativity is below
Intent intent = new Intent(this, Screenshots.class);
intent.putExtra("image", bm);
//"image" is my extra
startActivity(intent);
I send that while its saving, to an ImageView in a second(normal) activity. WORKS FINE
Code:
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screenshots);
//The ImageView where the screenshot goes
ImageView image=(ImageView)findViewById(R.id.image4);
//This "imageId" isnt used, but for some reason the Imageview wont set without it
Intent intent = getIntent();
int imageId = intent.getIntExtra("imageId", -1); // -1 would be a default value//
//this gets my extra
Bitmap bm = (Bitmap)this.getIntent().getParcelableExtra("image");
image.setImageBitmap(bm);
I have a button to share it, it opens with picture attached. SORT OF WORKING
The thing is, I want to automatically pass this same extra Bitmap and attach it to the message.
i can open a message with a known file attached.
Code:
{
Uri smsUri = Uri.parse("tel:0000000");
Intent intent = new Intent(Intent.ACTION_SEND, smsUri);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/folder/screenshot.png"));
intent.putExtra(Intent.EXTRA_TEXT,"Today");
startActivity(intent);
i tried the working in putExtra to the message, but I get a toast from the messaging app "Sorry, cannot attach this image". NO STACK ERRORS. nothign in the logs I can use.
Code:
Uri smsUri = Uri.parse("tel:0000000");
Intent intent = new Intent(Intent.ACTION_SEND, smsUri);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("image"));
intent.putExtra(Intent.EXTRA_TEXT,"Today");
startActivity(intent);
and other stuff like that that.
I currently am loading a known file into the message and it works perfect. Problem is, I wont know the name of the file, because my screenshots get saved as image1, image2, etc. So it will be different in every case.
So im wondering if its even possible to pass and extra through twice like that, or if I should look into return the latest image in that sdcard folder with like lastIndexOf(), or something similar.
basically, is there a way to simply query find and attach the highest numbered file? without a GUI(i can do select from gallery, but am trying to make it more automated).
any thoughts would be appreciated.
P.S. i know about the lint errors and things, and somewhat sloppy self taught java, but its working. only worried about the image passing.
Click to expand...
Click to collapse
I would just pass the filename to the share intent. In your saving method return the file name and pass it to the Uri.
lastIndexOf is a bad idea. What will you do if somebody saves a file called "xyz" in the same directory? The app will send this every time. So store the filename and pass it to the Uri.
nikwen said:
I would just pass the filename to the share intent. In your saving method return the file name and pass it to the Uri.
lastIndexOf is a bad idea. What will you do if somebody saves a file called "xyz" in the same directory? The app will send this every time. So store the filename and pass it to the Uri.
Click to expand...
Click to collapse
Yeah I had originally tried going about it that, with like getFileStreamPath and things like that, tried about a dozen different things but couldnt get them working. best i can get is that "sorry cant add..." message from the messaging app, which tells me that its passing the image, but it cant attach for some unknown reason(too large doesn't seem right, cuz i can do it with the known file name).
im a dum dum a probably should put this util class
Code:
static String saveBitmap(Bitmap bitmap, String dir, String baseName) {
try {
File sdcard = Environment.getExternalStorageDirectory();
File pictureDir = new File(sdcard, dir);
pictureDir.mkdirs();
File f = null;
for (int i = 1; i < 200; ++i) {
String name = baseName + i + ".png";
f = new File(pictureDir, name);
if (!f.exists()) {
break;
}
}
if (!f.exists()) {
String name = f.getAbsolutePath();
FileOutputStream fos = new FileOutputStream(name);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
//how to get "name" in third activity
return name;
}
} catch (Exception e) {
} finally {
/*
if (fos != null) {
fos.close();
}
*/
}
return null;
}
So I have the name there, but just cant get it over to the messaging. I'm wondering if I should take the pic and automaticaaly pin it to the MMS, and skip the imageview part?
First: Please get a logcat.
Second: This should be working if you use the right path:
Code:
Uri smsUri = Uri.parse("tel:0000000");
Intent intent = new Intent(Intent.ACTION_SEND, smsUri);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, Uri.parse("<path here>"));
intent.putExtra(Intent.EXTRA_TEXT,"Today");
startActivity(intent);
(got it from your first post)
1. This is a for instance situtation of if i try sliding the extra or something else into Uri.parse()
E/Mms/compose( 1063): DRM error in onActivityResult()!
E/Mms/media( 1063): IOException caught while opening or reading stream
E/Mms/media( 1063): java.io.FileNotFoundException: No content provider: image
But the content of image makes it into the ImageView(as "getParcelableExtra("image"), just not in the MMS, so I don't know.
2. Yeah it works Perfect when I hardcode in a file( sdcard/folder/image1.png). attaches and sends perfect.
The problem is basically I have a loose understanding of how I should be doing this, and just cant figure out how I should properly be getting it to load.
Banging my head against the wall on this one. lol. :fingers-crossed:
out of ideas said:
1. This is a for instance situtation of if i try sliding the extra or something else into Uri.parse()
E/Mms/compose( 1063): DRM error in onActivityResult()!
E/Mms/media( 1063): IOException caught while opening or reading stream
E/Mms/media( 1063): java.io.FileNotFoundException: No content provider: image
But the content of image makes it into the ImageView(as "getParcelableExtra("image"), just not in the MMS, so I don't know.
2. Yeah it works Perfect when I hardcode in a file( sdcard/folder/image1.png). attaches and sends perfect.
The problem is basically I have a loose understanding of how I should be doing this, and just cant figure out how I should properly be getting it to load.
Banging my head against the wall on this one. lol. :fingers-crossed:
Click to expand...
Click to collapse
The problem is that you do not pass the right file name. So it cannot find the file.
---------- Post added at 07:55 PM ---------- Previous post was at 07:48 PM ----------
Change it to this and tell us the log output:
Code:
static String saveBitmap(Bitmap bitmap, String dir, String baseName) {
try {
File sdcard = Environment.getExternalStorageDirectory();
File pictureDir = new File(sdcard, dir);
pictureDir.mkdirs();
File f = null;
for (int i = 1; i < 200; ++i) {
String name = baseName + i + ".png";
f = new File(pictureDir, name);
if (!f.exists()) {
break;
}
}
if (!f.exists()) {
Log.d("file", "file does not exist");
String name = f.getAbsolutePath();
FileOutputStream fos = new FileOutputStream(name);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
//how to get "name" in third activity
if (name != null) {
Log.d("return", name);
} else {
Log.d("return", "name = null");
}
return name;
} else {
Log.d("file", "file exists");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
/*
if (fos != null) {
fos.close();
}
*/
}
Log.d("return", "null");
return null;
}
I just inserted some debugging things. Check the logcat (and post it).
Did you add this to your manifest?
Code:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
nikwen said:
The problem is that you do not pass the right file name. So it cannot find the file.
I just inserted some debugging things. Check the logcat (and post it).
Did you add this to your manifest?
Code:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Click to expand...
Click to collapse
i know! I just need a way to get what my Util class returns as name. then open that attached to Message. It seems like it should be a lot easier than I am making it.
i added your logs, but the only match back I get is here (I put in some extra stuff)
Code:
D/ViewRoot( 2072): Dispatching pointer MotionEvent{2b00f540 action=1 x=85.33334 y=179.98325 pressure=0.20000002 size=0.20000002} to [email protected]
D/dalvikvm( 2072): GC_EXTERNAL_ALLOC freed 82K, 45% free 3083K/5575K, external 2159K/2284K, paused 57ms
//[B]THIS RIGHT BELOW HERE IS THE FILENAME. I NEED TO RETURN IT IN THE OTHER ACTIVITY. But How?
D/return ( 2072): /mnt/sdcard/folder/screen162.png
[/B]
I/ActivityManager( 182): Starting: Intent { cmp=com.myapp/.Screenshots (has extras) } from pid 2072
E/ActivityThread( 2072): >>> handling: 101
W/WindowManager( 182): Reached focused app: AppWindowToken{2b70bbf8 token=HistoryRecord{2b28ff08 com.myapp/.Screenshots}}
W/WindowManager( 182): updateFocusedWindowLocked newFocus=null mode=0 mCurrentFocus = Window{2b332630 PopupWindow:2afbd178 paused=false}
W/WindowManager( 182): Reached focused app: AppWindowToken{2b70bbf8 token=HistoryRecord{2b28ff08 com.myapp/.Screenshots}}
W/WindowManager( 182): updateFocusedWindowLocked newFocus=Window{2b408a60 com.myapp/com.myapp.Screenshots paused=false} mode=2 mCurrentFocus = Window{2b408a60 com.myapp/com.myapp.Screenshots paused=false}
W/WindowManager( 182): updateFocusedWindowLocked newFocus=Window{2b408a60 com.myapp/com.myapp.Screenshots paused=false} mode=3 mCurrentFocus = Window{2b408a60 com.myapp/com.myapp.Screenshots paused=false}
W/WindowManager( 182): Window Window{2b320c38 com.myapp/com.myapp.MainActivity paused=false} destroying surface Surface(name=com.myapp/com.myapp.MainActivity, identity=204), session Session{2b542460 uid 10050}
W/WindowManager( 182): Window Window{2b332630 PopupWindow:2afbd178 paused=false} destroying surface Surface(name=PopupWindow:2afbd178, identity=205), session Session{2b542460 uid 10050}
I/ActivityManager( 182): Displayed com.myapp/.Screenshots: +549ms
W/WindowManager( 182): Reached focused app: AppWindowToken{2b2dfeb8 token=HistoryRecord{2b395530 com.android.mms/.ui.ComposeMessageActivity}}
D/ActivityThread( 2072): <<< done: 106
W/WindowManager( 182): updateFocusedWindowLocked newFocus=null mode=3 mCurrentFocus = null
W/WindowManager( 182): Reached focused app: AppWindowToken{2b2dfeb8 token=HistoryRecord{2b395530 com.android.mms/.ui.ComposeMessageActivity}}
W/WindowManager( 182): Reached focused app: AppWindowToken{2b2dfeb8 token=HistoryRecord{2b395530 com.android.mms/.ui.ComposeMessageActivity}}
W/WindowManager( 182): Reached focused app: AppWindowToken{2b2dfeb8 token=HistoryRecord{2b395530 com.android.mms/.ui.ComposeMessageActivity}}
W/WindowManager( 182): updateFocusedWindowLocked newFocus=null mode=3 mCurrentFocus = null
W/WindowManager( 182): Reached focused app: AppWindowToken{2b2dfeb8 token=HistoryRecord{2b395530 com.android.mms/.ui.ComposeMessageActivity}}
W/WindowManager( 182): updateFocusedWindowLocked newFocus=null mode=3 mCurrentFocus = null
I/ActivityThread( 2081): Pub com.android.mms.SuggestionsProvider:
com.android.mms.SuggestionsProvider
E/MmsCustom( 2081): Mms,MmsCustom
E/MmsCustom( 2081): Init before calling function of doPreSotred()
E/MmsCustom( 2081): mms config have been prestored before
Yeah, I took 162 screenshots so far trying to get this. lol.
And yeah I declared the right permissions and everything. It takes the screenshot, saves it, and passes it to an ImageView in a different activity perfectly.
I can open Messaging, or FB,picassa, etc. It appends the text, but no image. BUT, i can simply hit attach from the opened message, and add in whatever picture I want.
I thought about just sending people into the gallery to pick, but the android numbering convention doesn't load images in sequential order, but a sort of numerical alphabetical( it saves likes 1, 10, 11,12,13,14,15,16,17,18,19,2,20,21,22,etc). At least this is with quickpic.
So they really get jumbled up, especially with 100+ in there(1, 10,100,11,12). And the point of this segment of the app is to share the most recent image.
i also dont want to just use the currentsystem time, because a ton of numbers is too confusing if they want to find a different one.
Thanks a lot for the help.
Let's try:
Code:
[COLOR="Red"]String path = Utils.saveBitmap(bitmap, dir, baseName);[/COLOR] //replace Utils by your class name
Uri smsUri = Uri.parse("tel:0000000");
Intent intent = new Intent(Intent.ACTION_SEND, smsUri);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, Uri.[COLOR="Red"]fromFile(path)[/COLOR]);
intent.putExtra(Intent.EXTRA_TEXT,"Today");
[COLOR="Red"]intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);[/COLOR]
startActivity(intent);
Took awhile to get Eclipse to accept it, but now I get
Code:
W/System.err( 2002): java.lang.NullPointerException
W/System.err( 2002): at com.MYAPP.Util.saveBitmap(Util.java:39)
//////The top red line you suggested
W/System.err( 2002): at com.MYAPP.Screenshots.onOptionsItemSelected(Screenshots.java:79)
W/System.err( 2002): at android.support.v4.app.Watson.onMenuItemSelected(Watson.java:119)
W/System.err( 2002): at com.actionbarsherlock.ActionBarSherlock.callbackOptionsItemSelected(ActionBarSherlock.java:603)
W/System.err( 2002): at com.actionbarsherlock.internal.ActionBarSherlockCompat.onMenuItemSelected(ActionBarSherlockCompat.java:529)
W/System.err( 2002): at com.actionbarsherlock.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:738)
W/System.err( 2002): at com.actionbarsherlock.internal.view.menu.SubMenuBuilder.dispatchMenuItemSelected(SubMenuBuilder.java:83)
W/System.err( 2002): at com.actionbarsherlock.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:148)
W/System.err( 2002): at com.actionbarsherlock.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:879)
W/System.err( 2002): at com.actionbarsherlock.internal.view.menu.MenuPopupHelper.onItemClick(MenuPopupHelper.java:158)
W/System.err( 2002): at android.widget.AdapterView.performItemClick(AdapterView.java:284)
W/System.err( 2002): at android.widget.ListView.performItemClick(ListView.java:3513)
W/System.err( 2002): at android.widget.AbsListView$PerformClick.run(AbsListView.java:1812)
W/System.err( 2002): at android.os.Handler.handleCallback(Handler.java:587)
W/System.err( 2002): at android.os.Handler.dispatchMessage(Handler.java:92)
W/System.err( 2002): at android.os.Looper.loop(Looper.java:130)
W/System.err( 2002): at android.app.ActivityThread.main(ActivityThread.java:3822)
W/System.err( 2002): at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err( 2002): at java.lang.reflect.Method.invoke(Method.java:507)
W/System.err( 2002): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
W/System.err( 2002): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
W/System.err( 2002): at dalvik.system.NativeStart.main(Native Method)
D/return ( 2002): null
D/AndroidRuntime( 2002): Shutting down VM
W/dalvikvm( 2002): threadid=1: thread exiting with uncaught exception (group=0x2aac4560)
E/AndroidRuntime( 2002): FATAL EXCEPTION: main
E/AndroidRuntime( 2002): java.lang.NullPointerException: uriString
E/AndroidRuntime( 2002): at android.net.Uri$StringUri.<init>(Uri.java:420)
E/AndroidRuntime( 2002): at android.net.Uri$StringUri.<init>(Uri.java:410)
E/AndroidRuntime( 2002): at android.net.Uri.parse(Uri.java:382)
//////The Changed Uri.getFile(); Line
E/AndroidRuntime( 2002): at com.MYAPP.Screenshots.onOptionsItemSelected(Screenshots.java:82)
E/AndroidRuntime( 2002): at android.support.v4.app.Watson.onMenuItemSelected(Watson.java:119)
E/AndroidRuntime( 2002): at com.actionbarsherlock.ActionBarSherlock.callbackOptionsItemSelected(ActionBarSherlock.java:603)
E/AndroidRuntime( 2002): at com.actionbarsherlock.internal.ActionBarSherlockCompat.onMenuItemSelected(ActionBarSherlockCompat.java:529)
E/AndroidRuntime( 2002): at com.actionbarsherlock.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:738)
E/AndroidRuntime( 2002): at com.actionbarsherlock.internal.view.menu.SubMenuBuilder.dispatchMenuItemSelected(SubMenuBuilder.java:83)
E/AndroidRuntime( 2002): at com.actionbarsherlock.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:148)
E/AndroidRuntime( 2002): at com.actionbarsherlock.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:879)
E/AndroidRuntime( 2002): at com.actionbarsherlock.internal.view.menu.MenuPopupHelper.onItemClick(MenuPopupHelper.java:158)
E/AndroidRuntime( 2002): at android.widget.AdapterView.performItemClick(AdapterView.java:284)
E/AndroidRuntime( 2002): at android.widget.ListView.performItemClick(ListView.java:3513)
E/AndroidRuntime( 2002): at android.widget.AbsListView$PerformClick.run(AbsListView.java:1812)
E/AndroidRuntime( 2002): at android.os.Handler.handleCallback(Handler.java:587)
E/AndroidRuntime( 2002): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime( 2002): at android.os.Looper.loop(Looper.java:130)
E/AndroidRuntime( 2002): at android.app.ActivityThread.main(ActivityThread.java:3822)
E/AndroidRuntime( 2002): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 2002): at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime( 2002): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
E/AndroidRuntime( 2002): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
E/AndroidRuntime( 2002): at dalvik.system.NativeStart.main(Native Method)
W/ActivityManager( 181): Force finishing activity com.MYAPP/.Screenshots
W/WindowManager( 181)
Starting to think I should just dump the whole imageview thing.
i need to figure out if i can save to SD how I am doing, and ALSO save to a cache (and overwrite other ones, so only one image persists there)
out of ideas said:
Took awhile to get Eclipse to accept it, but now I get
Code:
W/System.err( 2002): java.lang.NullPointerException
W/System.err( 2002): at com.MYAPP.Util.saveBitmap(Util.java:39)
//////The top red line you suggested
W/System.err( 2002): at com.MYAPP.Screenshots.onOptionsItemSelected(Screenshots.java:79)
W/System.err( 2002): at android.support.v4.app.Watson.onMenuItemSelected(Watson.java:119)
W/System.err( 2002): at com.actionbarsherlock.ActionBarSherlock.callbackOptionsItemSelected(ActionBarSherlock.java:603)
W/System.err( 2002): at com.actionbarsherlock.internal.ActionBarSherlockCompat.onMenuItemSelected(ActionBarSherlockCompat.java:529)
W/System.err( 2002): at com.actionbarsherlock.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:738)
W/System.err( 2002): at com.actionbarsherlock.internal.view.menu.SubMenuBuilder.dispatchMenuItemSelected(SubMenuBuilder.java:83)
W/System.err( 2002): at com.actionbarsherlock.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:148)
W/System.err( 2002): at com.actionbarsherlock.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:879)
W/System.err( 2002): at com.actionbarsherlock.internal.view.menu.MenuPopupHelper.onItemClick(MenuPopupHelper.java:158)
W/System.err( 2002): at android.widget.AdapterView.performItemClick(AdapterView.java:284)
W/System.err( 2002): at android.widget.ListView.performItemClick(ListView.java:3513)
W/System.err( 2002): at android.widget.AbsListView$PerformClick.run(AbsListView.java:1812)
W/System.err( 2002): at android.os.Handler.handleCallback(Handler.java:587)
W/System.err( 2002): at android.os.Handler.dispatchMessage(Handler.java:92)
W/System.err( 2002): at android.os.Looper.loop(Looper.java:130)
W/System.err( 2002): at android.app.ActivityThread.main(ActivityThread.java:3822)
W/System.err( 2002): at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err( 2002): at java.lang.reflect.Method.invoke(Method.java:507)
W/System.err( 2002): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
W/System.err( 2002): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
W/System.err( 2002): at dalvik.system.NativeStart.main(Native Method)
D/return ( 2002): null
D/AndroidRuntime( 2002): Shutting down VM
W/dalvikvm( 2002): threadid=1: thread exiting with uncaught exception (group=0x2aac4560)
E/AndroidRuntime( 2002): FATAL EXCEPTION: main
E/AndroidRuntime( 2002): java.lang.NullPointerException: uriString
E/AndroidRuntime( 2002): at android.net.Uri$StringUri.<init>(Uri.java:420)
E/AndroidRuntime( 2002): at android.net.Uri$StringUri.<init>(Uri.java:410)
E/AndroidRuntime( 2002): at android.net.Uri.parse(Uri.java:382)
//////The Changed Uri.getFile(); Line
E/AndroidRuntime( 2002): at com.MYAPP.Screenshots.onOptionsItemSelected(Screenshots.java:82)
E/AndroidRuntime( 2002): at android.support.v4.app.Watson.onMenuItemSelected(Watson.java:119)
E/AndroidRuntime( 2002): at com.actionbarsherlock.ActionBarSherlock.callbackOptionsItemSelected(ActionBarSherlock.java:603)
E/AndroidRuntime( 2002): at com.actionbarsherlock.internal.ActionBarSherlockCompat.onMenuItemSelected(ActionBarSherlockCompat.java:529)
E/AndroidRuntime( 2002): at com.actionbarsherlock.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:738)
E/AndroidRuntime( 2002): at com.actionbarsherlock.internal.view.menu.SubMenuBuilder.dispatchMenuItemSelected(SubMenuBuilder.java:83)
E/AndroidRuntime( 2002): at com.actionbarsherlock.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:148)
E/AndroidRuntime( 2002): at com.actionbarsherlock.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:879)
E/AndroidRuntime( 2002): at com.actionbarsherlock.internal.view.menu.MenuPopupHelper.onItemClick(MenuPopupHelper.java:158)
E/AndroidRuntime( 2002): at android.widget.AdapterView.performItemClick(AdapterView.java:284)
E/AndroidRuntime( 2002): at android.widget.ListView.performItemClick(ListView.java:3513)
E/AndroidRuntime( 2002): at android.widget.AbsListView$PerformClick.run(AbsListView.java:1812)
E/AndroidRuntime( 2002): at android.os.Handler.handleCallback(Handler.java:587)
E/AndroidRuntime( 2002): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime( 2002): at android.os.Looper.loop(Looper.java:130)
E/AndroidRuntime( 2002): at android.app.ActivityThread.main(ActivityThread.java:3822)
E/AndroidRuntime( 2002): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 2002): at java.lang.reflect.Method.invoke(Method.java:507)
E/AndroidRuntime( 2002): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
E/AndroidRuntime( 2002): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
E/AndroidRuntime( 2002): at dalvik.system.NativeStart.main(Native Method)
W/ActivityManager( 181): Force finishing activity com.MYAPP/.Screenshots
W/WindowManager( 181)
Starting to think I should just dump the whole imageview thing.
i need to figure out if i can save to SD how I am doing, and ALSO save to a cache (and overwrite other ones, so only one image persists there)
Click to expand...
Click to collapse
Post your code. We cannot help you if you just say "I changed this line."
It is not getFile but fromFile.
HaHa I know, im not trying to throw puzzles out at people randomly.
But the errors in the log were from those new lines(in red)
the string path
and fromFile path ones
I may be getting somewhere with this though, i found a little section on stackoverflow that i hadn't seen in the other 30 questions about images or screenshots. :fingers-crossed:
Plus i glad I always have about 5 other projects on can work on when I get stuck.
out of ideas said:
HaHa I know, im not trying to throw puzzles out at people randomly.
But the errors in the log were from those new lines(in red)
the string path
and fromFile path ones
I may be getting somewhere with this though, i found a little section on stackoverflow that i hadn't seen in the other 30 questions about images or screenshots. :fingers-crossed:
Plus i glad I always have about 5 other projects on can work on when I get stuck.
Click to expand...
Click to collapse
The problem occurs in the saveBitmap method. For that reason the path is null and then a NPE is thrown. Check your code to save the bitmap.

Camera Preview

Im trying to start a simple app and i need to display on a SurfaceView the preview of the cam as soon as the App start.
i added the permission to the manifest:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
and my code:
Code:
import android.content.Context;
import android.hardware.Camera;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class MainActivity extends SurfaceView implements SurfaceHolder.Callback{
SurfaceView mSurfaceView;
private SurfaceHolder mHolder;
public Camera camera = null;
public MainActivity(Context context) {
super(context);
mSurfaceView = (SurfaceView) findViewById(R.id.surfaceView);
mHolder = mSurfaceView.getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
[user=439709]@override[/user]
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
try{
camera.setPreviewDisplay(mHolder);
} catch(Exception e){
}
}
[user=439709]@override[/user]
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Camera.Parameters params = camera.getParameters();
params.setPreviewSize(width,height);
camera.setParameters(params);
camera.startPreview();
}
[user=439709]@override[/user]
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera = null;
}
}
Ive looked for many tutorial and all technically do the same or smiliart stuff. But the app crashes. I cant find a solution
LogCat
Code:
06-01 12:39:12.456 616-841/system_process I/ActivityManager: START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.example.droidcam/.MainActivity bnds=[240,408][240,408]} from pid 861
06-01 12:39:12.596 616-841/system_process D/dalvikvm: GC_FOR_ALLOC freed 1352K, 16% free 11518K/13560K, paused 112ms, total 118ms
06-01 12:39:12.636 2744-2744/? D/dalvikvm: Late-enabling CheckJNI
06-01 12:39:12.646 616-881/system_process I/ActivityManager: Start proc com.example.droidcam for activity com.example.droidcam/.MainActivity: pid=2744 uid=10019 gids={50019, 1006, 1028}
06-01 12:39:12.746 2744-2744/com.example.droidcam E/Trace: error opening trace file: No such file or directory (2)
06-01 12:39:12.826 2744-2744/com.example.droidcam D/dalvikvm: newInstance failed: no <init>()
06-01 12:39:12.836 2744-2744/com.example.droidcam D/AndroidRuntime: Shutting down VM
06-01 12:39:12.836 2744-2744/com.example.droidcam W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x2b5d9930)
06-01 12:39:12.836 2744-2744/com.example.droidcam E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.droidcam/com.example.droidcam.MainActivity}: java.lang.InstantiationException: can't instantiate class com.example.droidcam.MainActivity; no empty constructor
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2223)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2357)
at android.app.ActivityThread.access$600(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5226)
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:795)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.InstantiationException: can't instantiate class com.example.droidcam.MainActivity; no empty constructor
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1319)
at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2214)
... 11 more
06-01 12:39:12.836 616-1341/system_process W/ActivityManager: Force finishing activity com.example.droidcam/.MainActivity
06-01 12:39:12.986 616-650/system_process D/dalvikvm: GC_FOR_ALLOC freed 1696K, 24% free 10472K/13772K, paused 76ms, total 77ms
06-01 12:39:13.387 616-647/system_process W/ActivityManager: Activity pause timeout for ActivityRecord{2bd8aff0 u0 com.example.droidcam/.MainActivity}
06-01 12:39:18.952 2744-2744/? I/Process: Sending signal. PID: 2744 SIG: 9
06-01 12:39:18.952 616-943/system_process I/ActivityManager: Process com.example.droidcam (pid 2744) has died.
06-01 12:39:19.002 616-616/system_process W/InputMethodManagerService: Window already focused, ignoring focus gain of: [email protected] attribute=null, token = [email protected]
Please put your code into code tags.
EDIT: Thanks.
and Post/check logcats.
just saying it crashes is too vague.
out of ideas said:
and Post/check logcats.
just saying it crashes is too vague.
Click to expand...
Click to collapse
On Eclipse i know how to show the windows of the LogCat, but cant really find it here on Android Studio.
Im a bit newby about this sorry, coming from PHP using just Notepad.
Guess i found it, added log cat
I saw some tutorial like this, im not sure why it doesnt start.
Is it for te onCreate method missing? but i saw that for other works anyway like this
Btw i've also triyed an other way, but stills give me errors. i could upload that one too, different logcat.
Hope one of the two could be solved
Code:
import android.app.Activity;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.io.IOException;
public class MainActivity extends Activity implements SurfaceHolder.Callback{
/* VARIABILI PRIVATE */
private SurfaceView mSurfaceView;
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;
/** Called when the activity is first created. */
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSurfaceView = (SurfaceView)findViewById(R.id.surfaceView);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
[user=439709]@override[/user]
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
Camera.Parameters params = mCamera.getParameters();
params.setPreviewSize(arg2, arg3);
mCamera.setParameters(params);
try {
//lancio la preview
mCamera.setPreviewDisplay(arg0);
mCamera.startPreview();
} catch (IOException e) {
//gestione errore
}
}
[user=439709]@override[/user]
public void surfaceCreated(SurfaceHolder holder) {
mCamera = Camera.open();
}
[user=439709]@override[/user]
public void surfaceDestroyed(SurfaceHolder holder) {
mCamera.stopPreview();
mCamera.release();
}
logcat
Code:
06-01 13:32:31.187 616-661/system_process I/ActivityManager: Start proc com.android.vending for service com.android.vending/com.google.android.finsky.services.ContentSyncService: pid=25552 uid=10005 gids={50005, 3003, 1015, 1028}
06-01 13:32:31.227 25552-25552/com.android.vending E/Trace: error opening trace file: No such file or directory (2)
06-01 13:32:31.387 616-841/system_process I/ActivityManager: START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.example.droidcam/.MainActivity bnds=[240,408][240,408]} from pid 861
06-01 13:32:31.437 25566-25566/? D/dalvikvm: Late-enabling CheckJNI
06-01 13:32:31.447 616-1341/system_process I/ActivityManager: Start proc com.example.droidcam for activity com.example.droidcam/.MainActivity: pid=25566 uid=10019 gids={50019, 1006, 1028}
06-01 13:32:31.607 25566-25566/com.example.droidcam E/Trace: error opening trace file: No such file or directory (2)
06-01 13:32:31.787 25552-25552/com.android.vending D/Finsky: [1] FinskyApp.onCreate: Initializing network with DFE https://android.clients.google.com/fdfe/
06-01 13:32:31.987 25552-25552/com.android.vending D/Finsky: [1] DailyHygiene.goMakeHygieneIfDirty: No need to run daily hygiene.
06-01 13:32:32.037 25552-25552/com.android.vending W/Settings: Setting download_manager_max_bytes_over_mobile has moved from android.provider.Settings.Secure to android.provider.Settings.Global.
06-01 13:32:32.037 25552-25552/com.android.vending W/Settings: Setting download_manager_recommended_max_bytes_over_mobile has moved from android.provider.Settings.Secure to android.provider.Settings.Global.
06-01 13:32:32.178 616-881/system_process D/dalvikvm: GC_FOR_ALLOC freed 656K, 26% free 11321K/15124K, paused 82ms, total 86ms
06-01 13:32:32.238 25566-25566/com.example.droidcam D/libEGL: loaded /system/lib/egl/libEGL_adreno200.so
06-01 13:32:32.258 25566-25566/com.example.droidcam D/libEGL: loaded /system/lib/egl/libGLESv1_CM_adreno200.so
06-01 13:32:32.258 25566-25566/com.example.droidcam D/libEGL: loaded /system/lib/egl/libGLESv2_adreno200.so
06-01 13:32:32.268 25566-25566/com.example.droidcam I/Adreno200-EGL: <qeglDrvAPI_eglInitialize:294>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_JB.04.01.01.00.036_msm8960_JB_CL2644550_release_AU (CL2644550)
Build Date: 07/31/12 Tue
Local Branch:
Remote Branch: quic/master
Local Patches: NONE
Reconstruct Branch: AU_LINUX_ANDROID_JB.04.01.01.00.036 + NOTHING
06-01 13:32:32.318 25566-25566/com.example.droidcam D/OpenGLRenderer: Enabling debug mode 0
06-01 13:32:32.348 256-515/? I/AwesomePlayer: setDataSource_l(URL suppressed)
06-01 13:32:32.378 256-25622/? D/MediaExtractor: returning default extractor
06-01 13:32:32.388 256-515/? I/AwesomePlayer: setDataSource_l(URL suppressed)
06-01 13:32:32.408 256-25626/? D/MediaExtractor: returning default extractor
06-01 13:32:32.408 256-515/? I/CameraClient: Opening camera 0
06-01 13:32:32.408 256-515/? W/ServiceManager: Permission failure: com.sonyericsson.permission.CAMERA_EXTENDED from uid=10019 pid=25566
06-01 13:32:32.438 256-25630/? I/caladbolg: 3348999538 cald_camctrl.c (6713) 25630 P [SVR] -945967758 + Cald_CamCtrl_PowerUp
06-01 13:32:32.438 256-25630/? I/caladbolg: 3348999630 cald_camctrl.c (7484) 25630 P [SVR] -945967666 + Cald_CamCtrl_FSM_Func_PowerUp
06-01 13:32:32.438 256-25630/? I/caladbolg: 3349003170 cald_hal_qct.c (2789) 25630 P [HAL] -945964126 + Cald_Hal_Qct_If_PowerUp
06-01 13:32:32.438 256-25630/? I/caladbolg: 3349003323 cald_hal_qct.c (2847) 25630 P [HAL] -945963973 - Cald_Hal_Qct_If_PowerUp (0)
06-01 13:32:32.438 256-25630/? I/caladbolg: 3349004665 cald_camctrl.c (7563) 25630 P [SVR] -945962631 - Cald_CamCtrl_FSM_Func_PowerUp (0)
06-01 13:32:32.438 256-25630/? I/caladbolg: 3349004726 cald_camctrl.c (6720) 25630 P [SVR] -945962570 - Cald_CamCtrl_PowerUp (0)
06-01 13:32:32.448 256-25630/? E/caladbolg: 3349014431 cald_camctrl.c (11888) 25630 E [SVR] PreviewSize Invalid param: value[402x527]
06-01 13:32:32.458 25566-25566/com.example.droidcam D/AndroidRuntime: Shutting down VM
06-01 13:32:32.458 25566-25566/com.example.droidcam W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x2b5d9930)
06-01 13:32:32.488 25566-25566/com.example.droidcam E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: setParameters failed
at android.hardware.Camera.native_setParameters(Native Method)
at android.hardware.Camera.setParameters(Camera.java:1496)
at com.example.droidcam.MainActivity.surfaceChanged(MainActivity.java:41)
at android.view.SurfaceView.updateWindow(SurfaceView.java:580)
at android.view.SurfaceView.access$000(SurfaceView.java:86)
at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:174)
at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:680)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1842)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
at android.view.Choreographer.doCallbacks(Choreographer.java:562)
at android.view.Choreographer.doFrame(Choreographer.java:532)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5226)
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:795)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
at dalvik.system.NativeStart.main(Native Method)
06-01 13:32:32.498 616-943/system_process W/ActivityManager: Force finishing activity com.example.droidcam/.MainActivity
06-01 13:32:32.688 25552-25552/com.android.vending D/Finsky: [1] 2.run: Loaded library for account: [i1YaFxIWaZrcOQ26zxNX5K0RvvY]
06-01 13:32:32.688 25552-25552/com.android.vending D/Finsky: [1] 2.run: Finished loading 1 libraries.
06-01 13:32:32.908 25552-25552/com.android.vending D/Finsky: [1] 5.onFinished: Installation state replication succeeded.
06-01 13:32:33.018 616-647/system_process W/ActivityManager: Activity pause timeout for ActivityRecord{2b946870 u0 com.example.droidcam/.MainActivity}
In Android you normally do not use the constructor of an Activity for anything.
Use the onCreate method instead.
EDIT: The log says that the constructor must be empty.
nikwen said:
In Android you normally do not use the constructor of an Activity for anything.
Use the onCreate method instead.
EDIT: The log says that the constructor must be empty.
Click to expand...
Click to collapse
I thought about that (even if i saw video tutorial doing it) so i tried wht onCreate method and now it seams to give problem with the setParameters?
Ive uploaded the new code and logcats before
Ah. Check this: http://stackoverflow.com/questions/3890381/camera-setparameters-failed-in-android
nikwen said:
Ah. Check this: http://stackoverflow.com/questions/3890381/camera-setparameters-failed-in-android
Click to expand...
Click to collapse
i tryed that at th beggin, and didnt work, in fact i tried it again and still give me the same error apparently
While I'm still learning myself, it looks like you are getting a failed camera permission. And then it tries to pass in an invalid parameter to the camera.
deniel said:
I/CameraClient: Opening camera 0
06-01 13:32:32.408 256-515/? W/ServiceManager: Permission failure: com.sonyericsson.permission.CAMERA_EXTENDED from uid=10019 pid=25566
06-01 13:32:32.448 256-25630/? E/caladbolg: 3349014431 cald_camctrl.c (11888) 25630 E [SVR] PreviewSize Invalid param: value[402x527]
[/CODE]
Click to expand...
Click to collapse
Sent from a Toasted Devil
netwokz said:
While I'm still learning myself, it looks like you are getting a failed camera permission. And then it tries to pass in an invalid parameter to the camera.
Sent from a Toasted Devil
Click to expand...
Click to collapse
But cant understand which one and how should i do. it ryed the 2 ways everybody does
What phone are you trying this on? Have you tried it in an emulator?
After getting home and I was able to try your second piece of code. It looks like it is a problem with <CODE>params.setPreviewSize(arg2, arg3);</CODE>, it doesn't like the width and height arguments. I found THIS(second answer). and after plugging it into your code it was working for me. If you like I can show you the modified code, altho its real easy to plug in.
netwokz said:
After getting home and I was able to try your second piece of code. It looks like it is a problem with <CODE>params.setPreviewSize(arg2, arg3);</CODE>, it doesn't like the width and height arguments. I found THIS(second answer). and after plugging it into your code it was working for me. If you like I can show you the modified code, altho its real easy to plug in.
Click to expand...
Click to collapse
i tryed his first example and finally i get his "distoted" image. When i'll have time ill try the rets thnk u very much
ill try this:
Code:
Camera.Size getBestPreviewSize(int width, int height, Camera.Parameters parameters) {
Camera.Size result=null;
float dr = Float.MAX_VALUE;
float ratio = (float)width/(float)height;
for (Camera.Size size : parameters.getSupportedPreviewSizes()) {
float r = (float)size.width/(float)size.height;
if( Math.abs(r - ratio) < dr && size.width <= width && size.height <= height ) {
dr = Math.abs(r - ratio);
result = size;
}
}
return result;
}
Code:
ublic void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Now that the size is known, set up the camera parameters and begin
// the preview.
if (isPreviewRunning) {
mCamera.stopPreview();
}
Camera.Parameters parameters = mCamera.getParameters();
List<Size> sizes = parameters.getSupportedPreviewSizes();
Size optimalSize = getBestPreviewSize( w, h, parameters);
parameters.setPreviewSize(optimalSize.width, optimalSize.height);
mCamera.setParameters(parameters);
mCamera.startPreview();
isPreviewRunning =true;
}
im not sure abot the 3rd parameter of the getBestPreviewSize method which one is it. Like this is still distorted
Yeah, I could never fix the distortion back when I was trying my camera app. But I think I will tinker with it again. Keep this updated if you find anything, I will also.
Sent from a Toasted Devil

Load layout in fragment

Hi guys. I've a problem woth fragment and layout. here is the code that give me error
MainActivity (I use onClick to load new fragment)
Code:
package com.croccio.bicimi4social.activity;
import org.holoeverywhere.ArrayAdapter;
import org.holoeverywhere.app.Activity;
import org.holoeverywhere.app.Fragment;
import org.holoeverywhere.widget.ListView;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.View;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.croccio.bicimi4social.Bicimi4Social;
import com.croccio.bicimi4social.R;
import com.croccio.bicimi4social.Utility.InternetConnection;
import com.croccio.bicimi4social.bikeSharing.BikeSharing;
import com.croccio.bicimi4social.fragment.FragmentGestionePostazioni;
import com.parse.Parse;
import com.parse.ParseAnalytics;
import com.sherlock.navigationdrawer.compat.SherlockActionBarDrawerToggle;
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private SherlockActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mTitles;
private InternetConnection ic;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bicimi4Social.bikeSharing=new BikeSharing(getSupportApplication());
ic = new InternetConnection(this);
ic.run();
Parse.initialize(this, "RxyJKRsDhoO7uwzfToILxNB7lMeLsSHXfrnpZ7sq", "6o3pJSeVXjF13MK7ZvLekPOdtj6RJMMHpEqM80cH");
ParseAnalytics.trackAppOpened(getIntent());
mTitle = mDrawerTitle = getTitle();
mTitles = getResources().getStringArray(R.array.sliding_menu_option);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new SherlockActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
//invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
//invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
[user=439709]@override[/user]
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
ic.setRunning(false);
}
[user=439709]@override[/user]
protected void onResume() {
// TODO Auto-generated method stub
Log.e("MAIN ACTIVITY", "ONRESUME");
ic.setRunning(true);
ic.run();
super.onResume();
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
[user=439709]@override[/user]
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
// menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
[user=439709]@override[/user]
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch(item.getItemId()) {
// case R.id.action_websearch:
// // create intent to perform web search for this planet
// Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
// intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
// // catch event that there's no activity to handle intent
// if (intent.resolveActivity(getPackageManager()) != null) {
// startActivity(intent);
// } else {
// Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
// }
// return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
[user=439709]@override[/user]
public void onItemClick(android.widget.AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
switch (position) {
case 0:
// update the main content by replacing fragments
Fragment fragment = new FragmentGestionePostazioni();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
break;
default:
break;
}
}
}
private void selectItem(int position) {
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
[user=439709]@override[/user]
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
[user=439709]@override[/user]
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
[user=439709]@override[/user]
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
here is fragment code
Code:
package com.croccio.bicimi4social.fragment;
import org.holoeverywhere.LayoutInflater;
import org.holoeverywhere.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import com.croccio.bicimi4social.R;
import com.croccio.bicimi4social.bikeSharing.BikeSharing;
import com.tjerkw.slideexpandable.library.ActionSlideExpandableListView;
public class FragmentGestionePostazioni extends Fragment {
ActionSlideExpandableListView list;
BikeSharing bikeSharing;
Handler handler;
int click=0;
[user=439709]@override[/user]
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View root = inflater.inflate(
R.layout.gestione_postazioni, container, false);
root.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
root.setBackgroundResource(org.holoeverywhere.R.color.background_light);
return root;
}
[user=439709]@override[/user]
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
here is the layout for fragment
Code:
<android.support.v4.widget.SlidingPaneLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="@+id/slidingpanelayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="@+id/fragmentGestionePostazioniElenco"
android:name="com.croccio.bicimi4social.fragment.FragmentGestionePostazioniElenco"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/background_light" />
<fragment
android:id="@+id/fragmentGestionePostazioniMappe"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
map:cameraTargetLat="45.46545420"
map:cameraTargetLng="9.186515999999999"
map:cameraZoom="10"
map:mapType="normal"
map:uiRotateGestures="true"
map:uiScrollGestures="true"
map:uiTiltGestures="true"
map:uiZoomControls="false"
map:uiZoomGestures="true" />
</android.support.v4.widget.SlidingPaneLayout>
here is the logcat error
Code:
06-03 11:41:43.936: E/AndroidRuntime(19159): FATAL EXCEPTION: main
06-03 11:41:43.936: E/AndroidRuntime(19159): android.view.InflateException: Binary XML file line #7: Error inflating class fragment
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
06-03 11:41:43.936: E/AndroidRuntime(19159): at org.holoeverywhere.LayoutInflater.inflate(LayoutInflater.java:242)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
06-03 11:41:43.936: E/AndroidRuntime(19159): at org.holoeverywhere.LayoutInflater.inflate(LayoutInflater.java:227)
06-03 11:41:43.936: E/AndroidRuntime(19159): at com.croccio.bicimi4social.fragment.FragmentGestionePostazioni.onCreateView(FragmentGestionePostazioni.java:24)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.support.v4.app._HoloFragment.onCreateView(_HoloFragment.java:214)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:429)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.os.Handler.handleCallback(Handler.java:725)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.os.Handler.dispatchMessage(Handler.java:92)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.os.Looper.loop(Looper.java:137)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.app.ActivityThread.main(ActivityThread.java:5229)
06-03 11:41:43.936: E/AndroidRuntime(19159): at java.lang.reflect.Method.invokeNative(Native Method)
06-03 11:41:43.936: E/AndroidRuntime(19159): at java.lang.reflect.Method.invoke(Method.java:525)
06-03 11:41:43.936: E/AndroidRuntime(19159): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:799)
06-03 11:41:43.936: E/AndroidRuntime(19159): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
06-03 11:41:43.936: E/AndroidRuntime(19159): at dalvik.system.NativeStart.main(Native Method)
06-03 11:41:43.936: E/AndroidRuntime(19159): Caused by: java.lang.ClassCastException: com.croccio.bicimi4social.fragment.FragmentGestionePostazioniElenco cannot be cast to android.app.Fragment
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.app.Fragment.instantiate(Fragment.java:585)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.app.Fragment.instantiate(Fragment.java:560)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.app.Activity.onCreateView(Activity.java:4717)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:680)
06-03 11:41:43.936: E/AndroidRuntime(19159): ... 22 more
croccio said:
Hi guys. I've a problem woth fragment and layout. here is the code that give me error
Click to expand...
Click to collapse
This logcat line is interesting:
Code:
Caused by: java.lang.ClassCastException: com.croccio.bicimi4social.fragment.FragmentGestionePostazioniElenco cannot be cast to android.app.Fragment
I can think of two solutions:
1) Make sure your Fragment is a android.support.v4.app.Fragment and not a regular Fragment.
You'll have to add
Code:
import android.support.v4.app.Fragment;
to the FragmentGestionePostazioni file.
2) Try making your main Activity a FragmentActivity - change 'extends Activity' to 'extends FragmentActivity'
Hope that helps!
Alkonic said:
This logcat line is interesting:
Code:
Caused by: java.lang.ClassCastException: com.croccio.bicimi4social.fragment.FragmentGestionePostazioniElenco cannot be cast to android.app.Fragment
I can think of two solutions:
1) Make sure your Fragment is a android.support.v4.app.Fragment and not a regular Fragment.
You'll have to add
Code:
import android.support.v4.app.Fragment;
to the FragmentGestionePostazioni file.
2) Try making your main Activity a FragmentActivity - change 'extends Activity' to 'extends FragmentActivity'
Hope that helps!
Click to expand...
Click to collapse
thank you. i've used holo fragment and as i can't resolve the problem i changed layout and now it works. Thank you for your answer

[Q] what the correct way to use ShowcaseView?

when I try to use ShowcaseView I get error
Code:
@override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final ImageButton saveButton = (ImageButton) view.findViewById(R.id.button_Save);
ViewTarget viewTarget = new ViewTarget(saveButton);
showcaseView = new ShowcaseView.Builder(getActivity())
.setTarget(viewTarget)
.setContentTitle("Reset Button")
.setContentText("This will erase all the data in the table except the line that in progress")
.build();
}
when I tried to do the same thing in my fragmentactivity and didn't work, but when I did the same thing but took a view that declared in the fragmentactivity and not in the fragment it worked.
Logcat:
Code:
FATAL EXCEPTION: main
java.lang.IllegalArgumentException: width and height must be > 0
at android.graphics.Bitmap.createBitmap(Bitmap.java:724)
at android.graphics.Bitmap.createBitmap(Bitmap.java:703)
at android.graphics.Bitmap.createBitmap(Bitmap.java:670)
at com.github.amlcurran.showcaseview.ShowcaseView.updateBitmap(ShowcaseView.java:169)
at com.github.amlcurran.showcaseview.ShowcaseView.onGlobalLayout(ShowcaseView.java:343)
at android.view.ViewTreeObserver.dispatchOnGlobalLayout(ViewTreeObserver.java:839)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2050)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1249)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6364)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:791)
at android.view.Choreographer.doCallbacks(Choreographer.java:591)
at android.view.Choreographer.doFrame(Choreographer.java:561)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:777)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
I understand what the error said but how can I fix it?

Problem trying to get the camera function and selecting a image from gallery to work?

Hi still new to android, tried the following tutorial in the youtube link here https://www.youtube.com/watch?v=4LCnoVqQ6N4 but I couldn't get the app to work as I am unable to execute the camera on my physical phone where it kept giving me this popup "Something went Wrong while taking photos" when I press the camera imageview. And when I am at the gallery choosing a photo it will cause the app to suddenly stop.
Thus, I downloaded the author's source code here https://drive.google.com/file/d/0B2rvGRbu0A83cjBBZElhdGp5OHM/view but i also encounter the same issues stated above.
Tried adding the permission for camera,read,write external storage in the androidmanifest without any luck of solving it.
Error Log after i click on a image in the gallery:
Code:
08-17 12:21:08.181 17286-17286/com.example.user.cameratoserver E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.cameratoserver, PID: 17286
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=400, result=-1, data=Intent { dat=content://com.android.providers.media.documents/document/image:104460 flg=0x1 }} to activity {com.example.user.cameratoserver/com.example.user.cameratoserver.MainActivity}: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media from pid=17286, uid=10038 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
at android.app.ActivityThread.deliverResults(ActivityThread.java:3798)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3841)
at android.app.ActivityThread.access$1400(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1440)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:234)
at android.app.ActivityThread.main(ActivityThread.java:5526)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media from pid=17286, uid=10038 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
at android.os.Parcel.readException(Parcel.java:1627)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
at android.content.ContentProviderProxy.query(ContentProviderNative.java:427)
at android.content.ContentResolver.query(ContentResolver.java:497)
at android.content.ContentResolver.query(ContentResolver.java:439)
at com.kosalgeek.android.photoutil.RealPathUtil.getDataColumn(RealPathUtil.java:131)
at com.kosalgeek.android.photoutil.RealPathUtil.getRealPathFromURI_API19(RealPathUtil.java:62)
at com.kosalgeek.android.photoutil.GalleryPhoto.getPath(GalleryPhoto.java:49)
at com.example.user.cameratoserver.MainActivity.onActivityResult(MainActivity.java:100)
at android.app.Activity.dispatchActivityResult(Activity.java:6490)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3794)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3841)
at android.app.ActivityThread.access$1400(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1440)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:234)
at android.app.ActivityThread.main(ActivityThread.java:5526)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
if you are testing on a device running android marshmallow and above you should also write code to request the android.permission.READ_EXTERNAL_STORAGE permission at runtime.
Take a look at the following link for android developers https://developer.android.com/training/permissions/requesting.html
nemoc 23 said:
if you are testing on a device running android marshmallow and above you should also write code to request the android.permission.READ_EXTERNAL_STORAGE permission at runtime.
Take a look at the following link for android developers https://developer.android.com/training/permissions/requesting.html
Click to expand...
Click to collapse
Oh i see but I've read the documentation but still at a lost as to how to implement the codes from the documentation into the source code in the link above, as this is my first android development experience was feeling rather lost.
imso said:
Oh i see but I've read the documentation but still at a lost as to how to implement the codes from the documentation into the source code in the link above, as this is my first android development experience was feeling rather lost.
Click to expand...
Click to collapse
If you are below MM you just need to add the permission to the manifest.
Code:
<manifest>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</manifest>
If you are on MM or higher you need to add the permission the manifest and then ask for it at runtime.
Code:
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_CONTACTS) != PackageManager.READ_EXTERNAL_STORAGE) {
ActivityCompat.requestPermissions(thisActivity, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, CALLBACK_ID);
}
You will also need to handle the result of that on your activity:
Code:
@Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (requestCode == CALLBACK_ID) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Granted
} else {
// Not granted
}
}
}

Categories

Resources