android: save capture photo 0kb in the folder - java

after taking a photo, my photo display in activity, but when i check into folder, the size from my photo is 0kb, i have no idea why this happen, and when i take a photo again, the new photo not save in the folder that i wanted, this is my code :
{
File sdCard= Environment.getExternalStorageDirectory();
File path = new File (sdCard.getAbsolutePath() + "/android/data/spaj_foto");
path.mkdir();
File file= new File (path,"spaj_foto.png");
outputFileUri = Uri.fromFile(file);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri );
startActivityForResult(cameraIntent,TAKE_PHOTO_CODE );
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == TAKE_PHOTO_CODE) {
Bundle extras = data.getExtras();
Bitmap photo = (Bitmap) extras.get("data");
image_spaj.setImageBitmap(photo);
}
else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);
}
}
}
EDIT
this is my logcat :
09-26 17:57:38.072: E/AndroidRuntime(12498): FATAL EXCEPTION: main
09-26 17:57:38.072: E/AndroidRuntime(12498): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=null} to activity {org.example.touch/org.example.touch.FormSpaj}: java.lang.NullPointerException
09-26 17:57:38.072: E/AndroidRuntime(12498): at android.app.ActivityThread.deliverResults(ActivityThread.java:3179)
09-26 17:57:38.072: E/AndroidRuntime(12498): at android.app.ActivityThread.handleSendResult(ActivityThread.java:3222)
09-26 17:57:38.072: E/AndroidRuntime(12498): at android.app.ActivityThread.access$1100(ActivityThread.java:140)
09-26 17:57:38.072: E/AndroidRuntime(12498): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1276)
09-26 17:57:38.072: E/AndroidRuntime(12498): at android.os.Handler.dispatchMessage(Handler.java:99)
09-26 17:57:38.072: E/AndroidRuntime(12498): at android.os.Looper.loop(Looper.java:137)
09-26 17:57:38.072: E/AndroidRuntime(12498): at android.app.ActivityThread.main(ActivityThread.java:4895)
09-26 17:57:38.072: E/AndroidRuntime(12498): at java.lang.reflect.Method.invokeNative(Native Method)
09-26 17:57:38.072: E/AndroidRuntime(12498): at java.lang.reflect.Method.invoke(Method.java:511)
09-26 17:57:38.072: E/AndroidRuntime(12498): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:994)
09-26 17:57:38.072: E/AndroidRuntime(12498): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761)
09-26 17:57:38.072: E/AndroidRuntime(12498): at dalvik.system.NativeStart.main(Native Method)
09-26 17:57:38.072: E/AndroidRuntime(12498): Caused by: java.lang.NullPointerException
09-26 17:57:38.072: E/AndroidRuntime(12498): at org.example.touch.FormSpaj.onActivityResult(FormSpaj.java:990)
09-26 17:57:38.072: E/AndroidRuntime(12498): at android.app.Activity.dispatchActivityResult(Activity.java:5347)
09-26 17:57:38.072: E/AndroidRuntime(12498): at android.app.ActivityThread.deliverResults(ActivityThread.java:3175)
09-26 17:57:38.072: E/AndroidRuntime(12498): ... 11 more

You have created a new file. (blank)
And then started a camera intent.
But what you have not done, is told the camera intent where to save the image.
Thus, leaving you with a blank file.
File file= new File (path,"spaj_foto.png");
outputFileUri = Uri.fromFile(file);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri );
startActivityForResult(cameraIntent,TAKE_PHOTO_CODE );
Note, you do Not need to create the file, android camera intent will do that for you.
What you do need to do is pass the extra, so the intent knows where to save.
(you do still need to create the directory)

Related

How to start Activity in my adapter?

How can I start activity in adapter? I use this method in my adapter:
post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
context.startActivity(new Intent(context,asabani_cat.class));
}
});
But this worked just for fragment of my app, when I called this code in Activity App suddenly crashed!
Another question that I have, is it the good way to start activity in adapter?
my logcat:
11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: FATAL EXCEPTION: main 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: java.lang.NullPointerException 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at com.katibehpayam.mahdi.katibehpayam.adapter_common$7.onClick(adapter_common.java:266) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at android.view.View.performClick(View.java:4377) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at android.view.View$PerformClick.run(View.java:18044) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:725) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:92) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5306) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:511) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
You could try:
post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.getContext().startActivity(new Intent(v.getContext(),asabani_cat.class));
}
});
You should post the error from the Logcat so we can help you further. However from what you've shown I can find nothing inherently wrong with your code. Make sure your context is set correctly. Furthermore if you are already in an Activity you do not need to say
context.startActivity(new Intent(context,asabani_cat.class));
you can simply say
startActivity(new Intent(this, asabani_cat.class));
If you are not in an Activity then you need to pass the context like so
MyAdapter myAdapter = new MyAdapter(this);
Then inside your adapter set your context like this:
MyAdapter(Context context) {
this.context = context;
}
EDIT
Your logcat shows a null pointer exception is the cause of your crash. Can you please post the code from adapter_common.java at line 266? Thanks
In kotlin, on your view:
class YourClass: ArrayAdapter<Feature>(), View.OnClickListener{
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var yourView = inflater.inflate(mResource, parent, false)
yourView .setOnClickListener(){
onClick(convertView)
}
}
override fun onClick(v: View?) {
val intent = Intent(mContext, SeckondActivity::class.java)
mContext.startActivity(intent)
}
}

"resolveUri failed on bad bitmap uri: content://media/external/images/media/49644" Im unable to view the image

hello I'm a beginner in developing android apps.I've been doin a contacts app.
This is my java code where im unable to display image on my gui after selecting image from gallery.
Ive tested in ANDROID KITKAT IT DOESNT SHOW IMAGE.
But this code works successfully on ANDROID ICECREAM SANDWICH,IT DISPLAYS IMAGE AFTER CHOOSING FROM gallery.
contactimageview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent= new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"select image"),1);
}
});
}
public void onActivityResult(int reqCode,int resCode,Intent data) {
if (resCode == RESULT_OK) {
if (reqCode==1){
imageUri = data.getData();
contactimageview.setImageURI(data.getData());
}}
}
after i select the image i get the following log as below
I think there is a problem in onActivityResult method code.
01-30 23:04:04.271 30813-30813/com.example.dell4.contact W/ResolverActivity﹕ mLaunchedFromPackage=com.example.dell4.contact
01-30 23:04:04.606 30813-30813/com.example.dell4.contact D/AbsListView﹕ Get MotionRecognitionManager
01-30 23:04:04.706 30813-30813/com.example.dell4.contact D/dalvikvm﹕ GC_FOR_ALLOC freed 144K, 9% free 13792K/15016K, paused 13ms, total 13ms
01-30 23:04:06.711 30813-30813/com.example.dell4.contact W/IInputConnectionWrapper﹕ showStatusIcon on inactive InputConnection
01-30 23:04:06.991 30813-30813/com.example.dell4.contact D/AbsListView﹕ onDetachedFromWindow
01-30 23:04:12.641 30813-30813/com.example.dell4.contact W/ImageView﹕ Unable to open content: content://media/external/images/media/49644
java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media/49644 from pid=30813, uid=10020 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
at android.os.Parcel.readException(Parcel.java:1465)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:185)
at android.database.DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(DatabaseUtils.java:148)
at android.content.ContentProviderProxy.openTypedAssetFile(ContentProviderNative.java:682)
at android.content.ContentResolver.openTypedAssetFileDescriptor(ContentResolver.java:1067)
at android.content.ContentResolver.openAssetFileDescriptor(ContentResolver.java:907)
at android.content.ContentResolver.openInputStream(ContentResolver.java:632)
at android.widget.ImageView.resolveUri(ImageView.java:674)
at android.widget.ImageView.setImageURI(ImageView.java:409)
at com.example.dell4.contact.MainActivity.onActivityResult(MainActivity.java:94)
at android.app.Activity.dispatchActivityResult(Activity.java:5643)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3677)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3724)
at android.app.ActivityThread.access$1400(ActivityThread.java:175)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1356)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5602)
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:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
01-30 23:04:12.641 30813-30813/com.example.dell4.contact I/System.out﹕ resolveUri failed on bad bitmap uri: content://media/external/images/media/49644
You need to add the permission <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> to your manifest file.

Android NetworkOnMainThreadException exception

I had this Networkonmainthread exception in my activity. I searched for a solution for the problem. While I was searching, I found that I should use AsyncTask. After I tried AsyncTask, I am still facing the same problem.
This is my register activity:
private class MyAsyncTask extends AsyncTask<String, Void, JSONObject> {
protected JSONObject doInBackground(String... params) {
UserFunctions userFunction = new UserFunctions();
if (params.length != 3)
return null;
JSONObject json = userFunction.registerUser(params[0], params[1], params[2]);
return json;
}
protected void onPostExecute(JSONObject json) {
// check for login response
try {
if (json != null && json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
UserFunctions userFunction = new UserFunctions();
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}else{
// Error in registration
registerErrorMsg.setText("Error occured in registration");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
// Importing all assets like buttons, text fields
inputFullName = (EditText) findViewById(R.id.registerName);
inputEmail = (EditText) findViewById(R.id.registerEmail);
inputPassword = (EditText) findViewById(R.id.registerPassword);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
registerErrorMsg = (TextView) findViewById(R.id.register_error);
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
new MyAsyncTask().execute(name, email, password);
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}else{
// Error in registration
registerErrorMsg.setText("Error occured in registration");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(i);
// Close Registration View
finish();
}
});
}
}
This is my logcat:
09-26 00:56:23.865: D/AndroidRuntime(791): Shutting down VM
09-26 00:56:23.875: W/dalvikvm(791): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
09-26 00:56:23.925: E/AndroidRuntime(791): FATAL EXCEPTION: main
09-26 00:56:23.925: E/AndroidRuntime(791): android.os.NetworkOnMainThreadException
09-26 00:56:23.925: E/AndroidRuntime(791): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
09-26 00:56:23.925: E/AndroidRuntime(791): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
09-26 00:56:23.925: E/AndroidRuntime(791): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
09-26 00:56:23.925: E/AndroidRuntime(791): at libcore.io.IoBridge.connect(IoBridge.java:112)
09-26 00:56:23.925: E/AndroidRuntime(791): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
09-26 00:56:23.925: E/AndroidRuntime(791): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
09-26 00:56:23.925: E/AndroidRuntime(791): at java.net.Socket.connect(Socket.java:842)
09-26 00:56:23.925: E/AndroidRuntime(791): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
09-26 00:56:23.925: E/AndroidRuntime(791): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
09-26 00:56:23.925: E/AndroidRuntime(791): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
09-26 00:56:23.925: E/AndroidRuntime(791): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
09-26 00:56:23.925: E/AndroidRuntime(791): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
09-26 00:56:23.925: E/AndroidRuntime(791): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
09-26 00:56:23.925: E/AndroidRuntime(791): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
09-26 00:56:23.925: E/AndroidRuntime(791): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
09-26 00:56:23.925: E/AndroidRuntime(791): at library.JSONParser.getJSONFromUrl(JSONParser.java:45)
09-26 00:56:23.925: E/AndroidRuntime(791): at library.UserFunctions.registerUser(UserFunctions.java:62)
09-26 00:56:23.925: E/AndroidRuntime(791): at com.example.bustracker.RegisterActivity$1.onClick(RegisterActivity.java:105)
09-26 00:56:23.925: E/AndroidRuntime(791): at android.view.View.performClick(View.java:4084)
09-26 00:56:23.925: E/AndroidRuntime(791): at android.view.View$PerformClick.run(View.java:16966)
09-26 00:56:23.925: E/AndroidRuntime(791): at android.os.Handler.handleCallback(Handler.java:615)
09-26 00:56:23.925: E/AndroidRuntime(791): at android.os.Handler.dispatchMessage(Handler.java:92)
09-26 00:56:23.925: E/AndroidRuntime(791): at android.os.Looper.loop(Looper.java:137)
09-26 00:56:23.925: E/AndroidRuntime(791): at android.app.ActivityThread.main(ActivityThread.java:4745)
09-26 00:56:23.925: E/AndroidRuntime(791): at java.lang.reflect.Method.invokeNative(Native Method)
09-26 00:56:23.925: E/AndroidRuntime(791): at java.lang.reflect.Method.invoke(Method.java:511)
09-26 00:56:23.925: E/AndroidRuntime(791): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
09-26 00:56:23.925: E/AndroidRuntime(791): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-26 00:56:23.925: E/AndroidRuntime(791): at dalvik.system.NativeStart.main(Native Method)
09-26 00:56:24.215: W/System.err(791): org.apache.http.conn.HttpHostConnectException: Connection to http:// refused
09-26 00:56:24.436: W/System.err(791): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:183)
09-26 00:56:24.546: W/System.err(791): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
09-26 00:56:24.786: W/System.err(791): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
09-26 00:56:24.967: W/System.err(791): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
09-26 00:56:24.995: W/System.err(791): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
09-26 00:56:25.017: W/System.err(791): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
09-26 00:56:25.017: W/System.err(791): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
09-26 00:56:25.165: W/System.err(791): at library.JSONParser.getJSONFromUrl(JSONParser.java:45)
09-26 00:56:25.235: W/System.err(791): at library.UserFunctions.registerUser(UserFunctions.java:62)
09-26 00:56:25.264: W/System.err(791): at com.example.bustracker.RegisterActivity$MyAsyncTask.doInBackground(RegisterActivity.java:43)
09-26 00:56:25.265: W/System.err(791): at com.example.bustracker.RegisterActivity$MyAsyncTask.doInBackground(RegisterActivity.java:1)
09-26 00:56:25.285: W/System.err(791): at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-26 00:56:25.305: W/System.err(791): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
09-26 00:56:25.535: W/System.err(791): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
09-26 00:56:25.535: W/System.err(791): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
09-26 00:56:25.675: W/System.err(791): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
09-26 00:56:25.956: W/System.err(791): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
09-26 00:56:26.115: W/System.err(791): at java.lang.Thread.run(Thread.java:856)
09-26 00:56:26.147: W/System.err(791): Caused by: java.net.ConnectException: failed to connect to /127.0.0.1 (port 8888): connect failed: ECONNREFUSED (Connection refused)
09-26 00:56:26.226: W/System.err(791): at libcore.io.IoBridge.connect(IoBridge.java:114)
09-26 00:56:26.226: W/System.err(791): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
09-26 00:56:26.236: W/System.err(791): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
09-26 00:56:26.236: W/System.err(791): at java.net.Socket.connect(Socket.java:842)
09-26 00:56:26.246: W/System.err(791): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
09-26 00:56:26.255: W/System.err(791): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
09-26 00:56:26.255: W/System.err(791): ... 17 more
09-26 00:56:26.266: W/System.err(791): Caused by: libcore.io.ErrnoException: connect failed: ECONNREFUSED (Connection refused)
09-26 00:56:26.276: W/System.err(791): at libcore.io.Posix.connect(Native Method)
09-26 00:56:26.286: W/System.err(791): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:85)
09-26 00:56:26.286: W/System.err(791): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
09-26 00:56:26.286: W/System.err(791): at libcore.io.IoBridge.connect(IoBridge.java:112)
09-26 00:56:26.296: W/System.err(791): ... 22 more
09-26 00:56:26.296: E/Buffer Error(791): Error converting result java.lang.NullPointerException
09-26 00:56:26.305: E/JSON Parser(791): Error parsing data org.json.JSONException: End of input at character 0 of
09-26 00:56:27.146: I/Process(791): Sending signal. PID: 791 SIG: 9
What am I doing wrong?
The stacktrace says you're calling a network operation in getJSONFromUrl() and calling that on the UI thread in registerUser(). The code here looks to be the culprit:
new MyAsyncTask().execute(name, email, password);
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, password);
You're first invoking the registerUser() in a background asynctask (good!) and then only a couple of lines later doing the same again on the main thread (bad!). Remove the latter.
I bet userFunction.logoutUser(getApplicationContext()); issues network request to logout user thus error caused by accessing network on main thread (onPostResult runs on ui thread, in contrary to doInBackground)
According to the code in your post, you're still calling userFunction.registerUser directly from inside of the onClickListener handler - right after calling MyAsyncTask.execute. It's that registerUser call that the logcat output is complaining about, not the one in the AsyncTask. Did you mean to delete the duplicate call from the onClickListener handler after you moved that logic to the AsyncTask?

Location based android application error

When i run app it give message unfortunately loca has stopped and close app
Java coding
package com.example.loca;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener {
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat, place1, currentlocation, btn_text;
String provider;
protected String latitude,longitude;
protected boolean gps_enabled,network_enabled;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
Toast.makeText(getApplicationContext(), currentlocation , Toast.LENGTH_LONG).show();
}
#Override
public void onLocationChanged(Location location) {
Toast.makeText(getApplicationContext(), currentlocation , Toast.LENGTH_LONG).show();
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
AND LOGCAT is
05-14 01:20:39.210: D/AndroidRuntime(1177): Shutting down VM
05-14 01:20:39.210: W/dalvikvm(1177): threadid=1: thread exiting with uncaught exception (group=0xb3aebb90)
05-14 01:20:39.230: E/AndroidRuntime(1177): FATAL EXCEPTION: main
05-14 01:20:39.230: E/AndroidRuntime(1177): Process: com.example.loca, PID: 1177
05-14 01:20:39.230: E/AndroidRuntime(1177): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.loca/com.example.loca.MainActivity}: java.lang.SecurityException: "gps" location provider requires ACCESS_FINE_LOCATION permission.
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.app.ActivityThread.access$700(ActivityThread.java:135)
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.os.Handler.dispatchMessage(Handler.java:102)
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.os.Looper.loop(Looper.java:137)
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.app.ActivityThread.main(ActivityThread.java:4998)
05-14 01:20:39.230: E/AndroidRuntime(1177): at java.lang.reflect.Method.invokeNative(Native Method)
05-14 01:20:39.230: E/AndroidRuntime(1177): at java.lang.reflect.Method.invoke(Method.java:515)
05-14 01:20:39.230: E/AndroidRuntime(1177): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
05-14 01:20:39.230: E/AndroidRuntime(1177): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
05-14 01:20:39.230: E/AndroidRuntime(1177): at dalvik.system.NativeStart.main(Native Method)
05-14 01:20:39.230: E/AndroidRuntime(1177): Caused by: java.lang.SecurityException: "gps" location provider requires ACCESS_FINE_LOCATION permission.
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.os.Parcel.readException(Parcel.java:1461)
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.os.Parcel.readException(Parcel.java:1415)
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.location.ILocationManager$Stub$Proxy.requestLocationUpdates(ILocationManager.java:540)
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.location.LocationManager.requestLocationUpdates(LocationManager.java:860)
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.location.LocationManager.requestLocationUpdates(LocationManager.java:454)
05-14 01:20:39.230: E/AndroidRuntime(1177): at com.example.loca.MainActivity.onCreate(MainActivity.java:34)
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.app.Activity.performCreate(Activity.java:5243)
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-14 01:20:39.230: E/AndroidRuntime(1177): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
05-14 01:20:39.230: E/AndroidRuntime(1177): ... 11 more
05-14 01:20:47.040: I/Process(1177): Sending signal. PID: 1177 SIG: 9
You need to request the FINE_LOCATION permission, just like the exception says.
Your logcat clearly said
Caused by: java.lang.SecurityException: "gps" location provider
requires ACCESS_FINE_LOCATION permission. 05-14 01:20:39.230:
E/AndroidRuntime(1177):
You need to add below permission in your manifest.xml file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
The log says it all :
location provider requires ACCESS_FINE_LOCATION permission.
Add this permission in AndroidManifest.xml and your app will work fine.

Alert dialog not functioning correctly.

This code I am working on requires the user to press a button after entering a phone number into a text box. The button is made to save the number.
When I run the code I want to have it present the user with an alert dialog asking them to enter a number if they pressed the button with no number present.
Instead of getting the alert dialog the app crashes. But with a number entered the app works just fine.
Any advice on this would be awesome - Here is the code with the stack trace under that.
-Thank you!
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//Create an if statement that brings up an alert dialog if there is no number entered into the field.
switch (v.getId()) {
case R.id.btnwidgetconfig: {
if (sharedData == null)
{
AlertDialog.Builder alert = new AlertDialog.Builder(c);
alert.setTitle("No number entered");
alert.setMessage("Please enter a phone number using the the text box");
alert.setCancelable(false);
alert.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivityForResult(
new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS),
0);
}
});
}
else
{
String stringData = sharedData.getText().toString();
Long l = Long.parseLong(stringData);
SharedPreferences.Editor editor = prefs.edit();
prefs.edit().putLong(constants.KEY, l).commit();
Toast.makeText(c, "Your number has been saved!",
Toast.LENGTH_LONG).show();
svNum.setText("Saved Number: " + prefs.getLong(constants.KEY, 411));
break;
}
}
}
}
});
////Stack Trace:
05-14 12:29:07.679: W/dalvikvm(30842): threadid=1: thread exiting with uncaught exception (group=0x40018560)
05-14 12:29:07.679: E/AndroidRuntime(30842): FATAL EXCEPTION: main
05-14 12:29:07.679: E/AndroidRuntime(30842): java.lang.NumberFormatException:
05-14 12:29:07.679: E/AndroidRuntime(30842): at java.lang.Long.parseLong(Long.java:337)
05-14 12:29:07.679: E/AndroidRuntime(30842): at java.lang.Long.parseLong(Long.java:311)
05-14 12:29:07.679: E/AndroidRuntime(30842): at example.save.phonenum.Settings$1.onClick(WWSettings.java:106)
05-14 12:29:07.679: E/AndroidRuntime(30842): at android.view.View.performClick(View.java:2485)
05-14 12:29:07.679: E/AndroidRuntime(30842): at android.view.View$PerformClick.run(View.java:9080)
05-14 12:29:07.679: E/AndroidRuntime(30842): at android.os.Handler.handleCallback(Handler.java:587)
05-14 12:29:07.679: E/AndroidRuntime(30842): at android.os.Handler.dispatchMessage(Handler.java:92)
05-14 12:29:07.679: E/AndroidRuntime(30842): at android.os.Looper.loop(Looper.java:130)
05-14 12:29:07.679: E/AndroidRuntime(30842): at android.app.ActivityThread.main(ActivityThread.java:3683)
05-14 12:29:07.679: E/AndroidRuntime(30842): at java.lang.reflect.Method.invokeNative(Native Method)
05-14 12:29:07.679: E/AndroidRuntime(30842): at java.lang.reflect.Method.invoke(Method.java:507)
05-14 12:29:07.679: E/AndroidRuntime(30842): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
05-14 12:29:07.679: E/AndroidRuntime(30842): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
05-14 12:29:07.679: E/AndroidRuntime(30842): at dalvik.system.NativeStart.main(Native Method)
05-14 12:29:15.569: W/IInputConnectionWrapper(30870): showStatusIcon on inactive InputConnection
I'm guessing this sharedData is a TextView. Which you are still trying to parse the result when it is null, hence the NFE. Put in a check to only run that code if there is a valid number. You are checking if it is null, which the TextView may not be but the contents are an empty String which you are trying to parse
Change
if (sharedData == null)
to something like
if (sharedData == null || sharedData.getText().toString().equals(""))
{
...
I would try to get the text before that line into your stringData variable then check if that is empty. Also, you will want to put a try/catch around the parsing code in case they try to enter a non-digit and display a message, unless you've already done that

Categories