not able to read back protobuff from file - java

i am writing a protobuf into file and then reading again as follows
protobuff block
Person personOne =
Person.newBuilder()
.setId(1234)
.setName("John Doe")
.setEmail("jdoe#example.com")
.addPhone(
Person.PhoneNumber.newBuilder()
.setNumber("555-4321")
.setType(Person.PhoneType.HOME))
.build();
writing to file , here data is byte[] and parameter is personOne.toByteArray()
try {
FileOutputStream output = new FileOutputStream(file);
output.write(data);
output.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
reading from file , but while reading i am getting error
try {
FileInputStream input = new FileInputStream(file);
byte [] buffer = new byte[input.read()];
input.read(buffer);
input.close();
return buffer;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
error
03-20 21:04:39.060: W/System.err(18074): com.google.protobuf.InvalidProtocolBufferException: Protocol message tag had invalid wire type.
03-20 21:04:39.090: W/System.err(18074): at com.google.protobuf.UnknownFieldSet$Builder.mergeFieldFrom(UnknownFieldSet.java:498)
03-20 21:04:39.110: W/System.err(18074): at com.google.protobuf.GeneratedMessage.parseUnknownField(GeneratedMessage.java:193)
03-20 21:04:39.110: W/System.err(18074): at com.example.protodemo.AddressBookProtos$Person.<init>(AddressBookProtos.java:124)
03-20 21:04:39.110: W/System.err(18074): at com.example.protodemo.AddressBookProtos$Person.<init>(AddressBookProtos.java:107)
03-20 21:04:39.110: W/System.err(18074): at com.example.protodemo.AddressBookProtos$Person$1.parsePartialFrom(AddressBookProtos.java:186)
03-20 21:04:39.110: W/System.err(18074): at com.example.protodemo.AddressBookProtos$Person$1.parsePartialFrom(AddressBookProtos.java:1)
03-20 21:04:39.110: W/System.err(18074): at com.google.protobuf.AbstractParser.parsePartialFrom(AbstractParser.java:141)
03-20 21:04:39.110: W/System.err(18074): at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:176)
03-20 21:04:39.110: W/System.err(18074): at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:188)
03-20 21:04:39.110: W/System.err(18074): at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:193)
03-20 21:04:39.110: W/System.err(18074): at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:49)
03-20 21:04:39.120: W/System.err(18074): at com.example.protodemo.AddressBookProtos$Person.parseFrom(AddressBookProtos.java:1088)
03-20 21:04:39.120: W/System.err(18074): at com.example.protodemo.MainActivity.onCreate(MainActivity.java:63)
03-20 21:04:39.120: W/System.err(18074): at android.app.Activity.performCreate(Activity.java:4470)
03-20 21:04:39.120: W/System.err(18074): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1053)
03-20 21:04:39.120: W/System.err(18074): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1934)
03-20 21:04:39.120: W/System.err(18074): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
03-20 21:04:39.120: W/System.err(18074): at android.app.ActivityThread.access$600(ActivityThread.java:128)
03-20 21:04:39.120: W/System.err(18074): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
03-20 21:04:39.120: W/System.err(18074): at android.os.Handler.dispatchMessage(Handler.java:99)
03-20 21:04:39.120: W/System.err(18074): at android.os.Looper.loop(Looper.java:137)
03-20 21:04:39.120: W/System.err(18074): at android.app.ActivityThread.main(ActivityThread.java:4517)
03-20 21:04:39.120: W/System.err(18074): at java.lang.reflect.Method.invokeNative(Native Method)
03-20 21:04:39.120: W/System.err(18074): at java.lang.reflect.Method.invoke(Method.java:511)
03-20 21:04:39.130: W/System.err(18074): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
03-20 21:04:39.130: W/System.err(18074): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
03-20 21:04:39.130: W/System.err(18074): at dalvik.system.NativeStart.main(Native Method)
Update
previously i was storing data into data.txt file but now i have removed the exception and getting new error
03-20 21:25:58.920: W/System.err(18470): com.google.protobuf.InvalidProtocolBufferException: Protocol message tag had invalid wire type.
03-20 21:25:58.920: W/System.err(18470): at com.google.protobuf.UnknownFieldSet$Builder.mergeFieldFrom(UnknownFieldSet.java:498)
03-20 21:25:58.920: W/System.err(18470): at com.google.protobuf.GeneratedMessage.parseUnknownField(GeneratedMessage.java:193)
03-20 21:25:58.920: W/System.err(18470): at com.example.protodemo.AddressBookProtos$Person.<init>(AddressBookProtos.java:124)
03-20 21:25:58.920: W/System.err(18470): at com.example.protodemo.AddressBookProtos$Person.<init>(AddressBookProtos.java:107)
03-20 21:25:58.930: W/System.err(18470): at com.example.protodemo.AddressBookProtos$Person$1.parsePartialFrom(AddressBookProtos.java:186)
03-20 21:25:58.930: W/System.err(18470): at com.example.protodemo.AddressBookProtos$Person$1.parsePartialFrom(AddressBookProtos.java:1)
03-20 21:25:58.930: W/System.err(18470): at com.google.protobuf.AbstractParser.parsePartialFrom(AbstractParser.java:141)
03-20 21:25:58.930: W/System.err(18470): at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:176)
03-20 21:25:58.930: W/System.err(18470): at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:188)
03-20 21:25:58.930: W/System.err(18470): at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:193)
03-20 21:25:58.930: W/System.err(18470): at com.google.protobuf.AbstractParser.parseFrom(AbstractParser.java:49)
03-20 21:25:58.930: W/System.err(18470): at com.example.protodemo.AddressBookProtos$Person.parseFrom(AddressBookProtos.java:1088)
03-20 21:25:58.930: W/System.err(18470): at com.example.protodemo.MainActivity.onCreate(MainActivity.java:63)
03-20 21:25:58.930: W/System.err(18470): at android.app.Activity.performCreate(Activity.java:4470)
03-20 21:25:58.930: W/System.err(18470): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1053)
03-20 21:25:58.930: W/System.err(18470): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1934)
03-20 21:25:58.930: W/System.err(18470): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
03-20 21:25:58.940: W/System.err(18470): at android.app.ActivityThread.access$600(ActivityThread.java:128)
03-20 21:25:58.940: W/System.err(18470): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
03-20 21:25:58.940: W/System.err(18470): at android.os.Handler.dispatchMessage(Handler.java:99)
03-20 21:25:58.940: W/System.err(18470): at android.os.Looper.loop(Looper.java:137)
03-20 21:25:58.940: W/System.err(18470): at android.app.ActivityThread.main(ActivityThread.java:4517)
03-20 21:25:58.940: W/System.err(18470): at java.lang.reflect.Method.invokeNative(Native Method)
03-20 21:25:58.940: W/System.err(18470): at java.lang.reflect.Method.invoke(Method.java:511)
03-20 21:25:58.940: W/System.err(18470): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
03-20 21:25:58.940: W/System.err(18470): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
03-20 21:25:58.940: W/System.err(18470): at dalvik.system.NativeStart.main(Native Method)

From your code:
byte [] buffer = new byte[input.read()];
Here you appear to be reading the first byte of the input and using it as the size of the buffer. However, when you wrote the file, you didn't actually write a size in the first byte; you only wrote the data:
FileOutputStream output = new FileOutputStream(file);
output.write(data);
output.close();
Instead of reading the file content to a byte[], just pass the input stream itself to parseFrom, like:
FileInputStream input = new FileInputStream(file);
Person person = Person.parseFrom(input);
If you must read into a byte array, then allocate the array according to the actual size of the file, e.g. using File#length(). Or, actually write the message size before writing the message. (Don't write it as just a single byte, though, because then you'll have problems if your message is larger than 255 bytes.)

Related

taking and uploading a image to website in android studio photo not found

I'm very new to java and android studio i have about 5 days under my belt from just going at it but I've ran into a snag i need help figuring out how to have android studio recognize the file path of a photo.
This program should open and display a imageView on the mainActivity and when you click it it will open up the camera and allow you to take a photo after you take the photo it backs out into the mainActivity and displays the full resolution photo in the imageView and uploads the photo to a website running some php code listening for posts and writing them to the online storage folder
everything works fine except when it tries to upload the photo it will say no file exists ive checked the storage on the device the photo is there maybe its because i had to use a FileProvider to make the uri go from file to content in order to save the image the php scrip works so im in need of help solving the cant find the file issue thank you for your help in advanced
the project code is below
device:Galexy note 8
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.photo">
<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="#string/file_provider_authority"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_provider_paths" />
</provider>
</application>
</manifest>
MainActivity.java
package com.example.photo;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
public interface ApplicationConstant {
String UPLOAD_IMAGE_URL = "http://www.example.com/upload.php";
String TAG = "DEBUG1";
}
String Barcode="9999";
int permsRequestCode;
int RC_PERMISSIONS;
final int CAMERA_REQUEST = 1;
private Uri photoUri;
ImageView mImg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImg = (ImageView) findViewById(R.id.imageView);
mImg.setOnClickListener(new View.OnClickListener() {
//#Override
public void onClick(View v) {
Log.i(ApplicationConstant.TAG," " + "click");
showCamera();
}
});
}
private class uploadFileToServerTask extends AsyncTask<String, String, Object> {
#Override
protected String doInBackground(String... args) {
try {
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
#SuppressWarnings("PointlessArithmeticExpression")
int maxBufferSize = 1 * 1024 * 1024;
java.net.URL url = new URL((ApplicationConstant.UPLOAD_IMAGE_URL));
Log.i(ApplicationConstant.TAG, "url " + url);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs.
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Set HTTP method to POST.
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
FileInputStream fileInputStream;
DataOutputStream outputStream;
{
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
String filename = args[0];
outputStream.writeBytes("Content-Disposition: form-data; name=\"file\";filename=\"" + filename + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
Log.i(ApplicationConstant.TAG, "filename: " + filename);
fileInputStream = new FileInputStream(filename);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
}
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.i(ApplicationConstant.TAG, "serverResponseCode: " + serverResponseCode);
Log.i(ApplicationConstant.TAG, "serverResponseMessage: " + serverResponseMessage);
fileInputStream.close();
outputStream.flush();
outputStream.close();
if (serverResponseCode == 200) {
return "true";
}
} catch (Exception e) {
e.printStackTrace();
}
return "false";
}
#Override
protected void onPostExecute(Object result) {
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST) {
if (resultCode == RESULT_OK) {
if (photoUri != null) {
mImg.setImageURI(photoUri);
Log.i(ApplicationConstant.TAG,"photo_Uri: " + photoUri);
new uploadFileToServerTask().execute(photoUri.toString());
}
}
}
}
private void showCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(this.getPackageManager()) != null) {
File file = null;
try {
file = createImageFile();
} catch (IOException e) {
e.printStackTrace();
}
photoUri = null;
if (file != null) {
photoUri = FileProvider.getUriForFile(MainActivity.this,
getString(R.string.file_provider_authority),
file);
//photoUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(intent, CAMERA_REQUEST);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
File storageDir = new File(this.getExternalFilesDir(Environment.DIRECTORY_PICTURES),Barcode + ".jpg");
// File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return storageDir;
}
}
values/strings.xml
<resources>
<string name="app_name">Photo</string>
<string name="file_provider_authority" translatable="false">com.example.photo.fileprovider</string>
</resources>
xml/file_provider_path.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path
name="external_files" path="." />
</paths>
upload.php
<?php
$target_dir = "";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["file"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
Logcat
03-20 02:33:39.234 32312-32312/? E/Zygote: v2
03-20 02:33:39.235 32312-32312/? I/libpersona: KNOX_SDCARD checking this for 10276
03-20 02:33:39.235 32312-32312/? I/libpersona: KNOX_SDCARD not a persona
03-20 02:33:39.235 32312-32312/? E/Zygote: accessInfo : 0
03-20 02:33:39.236 32312-32312/? W/SELinux: SELinux selinux_android_compute_policy_index : Policy Index[2], Con:u:r:zygote:s0 RAM:SEPF_SECMOBILE_7.1.1_0004, [-1 -1 -1 -1 0 1]
03-20 02:33:39.236 32312-32312/? I/SELinux: SELinux: seapp_context_lookup: seinfo=untrusted, level=s0:c512,c768, pkgname=com.example.photo
03-20 02:33:39.241 32312-32312/? I/art: Late-enabling -Xcheck:jni
03-20 02:33:39.452 32312-32312/com.example.photo I/InstantRun: starting instant run server: is main process
03-20 02:33:39.510 32312-32312/com.example.photo V/ActivityThread: performLaunchActivity: mActivityCurrentConfig={0 1.0 themeSeq = 0 showBtnBg = 0 310mcc260mnc [en_US,ja_JP] ldltr sw411dp w411dp h773dp 560dpi nrml long port ?dc finger -keyb/v/h -nav/h mkbd/h desktop/d s.112}
03-20 02:33:39.522 32312-32312/com.example.photo W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
03-20 02:33:39.611 32312-32312/com.example.photo D/TextView: setTypeface with style : 0
03-20 02:33:39.612 32312-32312/com.example.photo D/TextView: setTypeface with style : 0
03-20 02:33:39.649 32312-32312/com.example.photo D/ViewRootImpl#4c4ddef[MainActivity]: ThreadedRenderer.create() translucent=false
03-20 02:33:39.653 32312-32312/com.example.photo D/InputTransport: Input channel constructed: fd=87
03-20 02:33:39.654 32312-32312/com.example.photo D/ViewRootImpl#4c4ddef[MainActivity]: setView = DecorView#94b80fc[MainActivity] touchMode=true
03-20 02:33:39.663 32312-32312/com.example.photo D/ViewRootImpl#4c4ddef[MainActivity]: dispatchAttachedToWindow
03-20 02:33:39.688 32312-32312/com.example.photo V/Surface: sf_framedrop debug : 0x4f4c, game : false, logging : 0
03-20 02:33:39.688 32312-32312/com.example.photo D/ViewRootImpl#4c4ddef[MainActivity]: Relayout returned: oldFrame=[0,0][0,0] newFrame=[0,0][1440,2960] result=0x27 surface={isValid=true 548279813120} surfaceGenerationChanged=true
03-20 02:33:39.688 32312-32312/com.example.photo D/ViewRootImpl#4c4ddef[MainActivity]: mHardwareRenderer.initialize() mSurface={isValid=true 548279813120} hwInitialized=true
03-20 02:33:39.691 32312-32379/com.example.photo D/libEGL: loaded /vendor/lib64/egl/libEGL_adreno.so
03-20 02:33:39.703 32312-32379/com.example.photo D/libEGL: loaded /vendor/lib64/egl/libGLESv1_CM_adreno.so
03-20 02:33:39.709 32312-32312/com.example.photo W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
03-20 02:33:39.711 32312-32379/com.example.photo D/libEGL: loaded /vendor/lib64/egl/libGLESv2_adreno.so
03-20 02:33:39.715 32312-32312/com.example.photo D/ViewRootImpl#4c4ddef[MainActivity]: MSG_RESIZED_REPORT: frame=Rect(0, 0 - 1440, 2960) ci=Rect(0, 84 - 0, 168) vi=Rect(0, 84 - 0, 168) or=1
03-20 02:33:39.715 32312-32312/com.example.photo D/ViewRootImpl#4c4ddef[MainActivity]: MSG_WINDOW_FOCUS_CHANGED 1
03-20 02:33:39.715 32312-32312/com.example.photo D/ViewRootImpl#4c4ddef[MainActivity]: mHardwareRenderer.initializeIfNeeded()#2 mSurface={isValid=true 548279813120}
03-20 02:33:39.716 32312-32312/com.example.photo V/InputMethodManager: Starting input: tba=android.view.inputmethod.EditorInfo#72b6a0b nm : com.example.photo ic=null
03-20 02:33:39.716 32312-32312/com.example.photo I/InputMethodManager: startInputInner - mService.startInputOrWindowGainedFocus
03-20 02:33:39.721 32312-32324/com.example.photo D/InputTransport: Input channel constructed: fd=95
03-20 02:33:39.725 32312-32379/com.example.photo I/Adreno: QUALCOMM build : 33f9106, Ia8660bee96
Build Date : 08/09/17
OpenGL ES Shader Compiler Version: XE031.14.00.01
Local Branch :
Remote Branch : refs/tags/AU_LINUX_ANDROID_LA.UM.5.7.C2.07.01.01.292.070
Remote Branch : NONE
Reconstruct Branch : NOTHING
03-20 02:33:39.726 32312-32379/com.example.photo I/Adreno: PFP: 0x005ff104, ME: 0x005ff063
03-20 02:33:39.727 32312-32379/com.example.photo I/OpenGLRenderer: Initialized EGL, version 1.4
03-20 02:33:39.727 32312-32379/com.example.photo D/OpenGLRenderer: Swap behavior 1
03-20 02:33:39.745 32312-32312/com.example.photo V/InputMethodManager: Starting input: tba=android.view.inputmethod.EditorInfo#b83b500 nm : com.example.photo ic=null
03-20 02:33:42.813 32312-32312/com.example.photo D/ViewRootImpl#4c4ddef[MainActivity]: ViewPostImeInputStage processPointer 0
03-20 02:33:42.888 32312-32312/com.example.photo D/ViewRootImpl#4c4ddef[MainActivity]: ViewPostImeInputStage processPointer 1
03-20 02:33:42.891 32312-32312/com.example.photo I/DEBUG1: click
03-20 02:33:42.915 32312-32312/com.example.photo D/ViewRootImpl#4c4ddef[MainActivity]: MSG_WINDOW_FOCUS_CHANGED 0
03-20 02:33:43.165 32312-32312/com.example.photo D/ViewRootImpl#4c4ddef[MainActivity]: mHardwareRenderer.destroy()#1
03-20 02:33:43.173 32312-32312/com.example.photo D/ViewRootImpl#4c4ddef[MainActivity]: Relayout returned: oldFrame=[0,0][1440,2960] newFrame=[0,0][1440,2960] result=0x5 surface={isValid=false 0} surfaceGenerationChanged=true
03-20 02:33:43.173 32312-32312/com.example.photo D/InputTransport: Input channel destroyed: fd=95
03-20 02:33:49.502 32312-32312/com.example.photo D/ViewRootImpl#4c4ddef[MainActivity]: mHardwareRenderer.destroy()#1
03-20 02:33:49.508 32312-32312/com.example.photo D/ViewRootImpl#4c4ddef[MainActivity]: Relayout returned: oldFrame=[0,0][1440,2960] newFrame=[0,0][1440,2960] result=0x1 surface={isValid=false 0} surfaceGenerationChanged=false
03-20 02:33:49.531 32312-32312/com.example.photo V/Surface: sf_framedrop debug : 0x4f4c, game : false, logging : 0
03-20 02:33:49.532 32312-32312/com.example.photo D/ViewRootImpl#4c4ddef[MainActivity]: Relayout returned: oldFrame=[0,0][1440,2960] newFrame=[0,0][1440,2960] result=0x7 surface={isValid=true 548279813120} surfaceGenerationChanged=true
03-20 02:33:49.532 32312-32312/com.example.photo D/ViewRootImpl#4c4ddef[MainActivity]: mHardwareRenderer.initialize() mSurface={isValid=true 548279813120} hwInitialized=true
03-20 02:33:49.545 32312-32312/com.example.photo D/ViewRootImpl#4c4ddef[MainActivity]: MSG_WINDOW_FOCUS_CHANGED 1
03-20 02:33:49.545 32312-32312/com.example.photo D/ViewRootImpl#4c4ddef[MainActivity]: mHardwareRenderer.initializeIfNeeded()#2 mSurface={isValid=true 548279813120}
03-20 02:33:49.545 32312-32312/com.example.photo V/InputMethodManager: Starting input: tba=android.view.inputmethod.EditorInfo#4c32418 nm : com.example.photo ic=null
03-20 02:33:49.545 32312-32312/com.example.photo I/InputMethodManager: startInputInner - mService.startInputOrWindowGainedFocus
03-20 02:33:49.547 32312-32312/com.example.photo D/InputTransport: Input channel constructed: fd=91
03-20 02:33:49.797 32312-32312/com.example.photo I/DEBUG1: photo_Uri: content://com.example.photo.fileprovider/external_files/Android/data/com.example.photo/files/Pictures/9999.jpg
03-20 02:33:49.799 32312-2026/com.example.photo I/DEBUG1: url http://www.example.com/upload.php
03-20 02:33:49.802 32312-2026/com.example.photo D/NetworkSecurityConfig: No Network Security Config specified, using platform default
03-20 02:33:49.803 32312-2026/com.example.photo I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
03-20 02:33:49.803 32312-2026/com.example.photo I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
03-20 02:33:49.903 32312-2026/com.example.photo D/TcpOptimizer: TcpOptimizer-ON
03-20 02:33:49.983 32312-2026/com.example.photo I/DEBUG1: filename: content://com.example.photo.fileprovider/external_files/Android/data/com.example.photo/files/Pictures/9999.jpg
03-20 02:33:49.983 32312-2026/com.example.photo W/System.err: java.io.FileNotFoundException: content:/com.example.photo.fileprovider/external_files/Android/data/com.example.photo/files/Pictures/9999.jpg (No such file or directory)
03-20 02:33:49.983 32312-2026/com.example.photo W/System.err: at java.io.FileInputStream.open(Native Method)
03-20 02:33:49.983 32312-2026/com.example.photo W/System.err: at java.io.FileInputStream.<init>(FileInputStream.java:146)
03-20 02:33:49.983 32312-2026/com.example.photo W/System.err: at java.io.FileInputStream.<init>(FileInputStream.java:99)
03-20 02:33:49.983 32312-2026/com.example.photo W/System.err: at com.example.photo.MainActivity$uploadFileToServerTask.doInBackground(MainActivity.java:94)
03-20 02:33:49.983 32312-2026/com.example.photo W/System.err: at com.example.photo.MainActivity$uploadFileToServerTask.doInBackground(MainActivity.java:55)
03-20 02:33:49.983 32312-2026/com.example.photo W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:305)
03-20 02:33:49.983 32312-2026/com.example.photo W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
03-20 02:33:49.983 32312-2026/com.example.photo W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
03-20 02:33:49.983 32312-2026/com.example.photo W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
03-20 02:33:49.983 32312-2026/com.example.photo W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
03-20 02:33:49.983 32312-2026/com.example.photo W/System.err: at java.lang.Thread.run(Thread.java:762)
03-20 02:33:52.113 32312-32312/com.example.photo D/ViewRootImpl#4c4ddef[MainActivity]: mHardwareRenderer.destroy()#4
03-20 02:33:52.113 32312-32312/com.example.photo D/ViewRootImpl#4c4ddef[MainActivity]: dispatchDetachedFromWindow
03-20 02:33:52.117 32312-32312/com.example.photo D/InputTransport: Input channel destroyed: fd=87
03-20 02:33:52.117 32312-32312/com.example.photo W/SemDesktopModeManager: unregisterListener: Listener is null
03-20 02:33:52.120 32312-32312/com.example.photo V/ActivityThread: performLaunchActivity: mActivityCurrentConfig={0 1.0 themeSeq = 0 showBtnBg = 0 310mcc260mnc [en_US,ja_JP] ldltr sw411dp w797dp h387dp 560dpi nrml long land ?dc finger -keyb/v/h -nav/h mkbd/h desktop/d s.113}
03-20 02:33:52.134 32312-32312/com.example.photo D/TextView: setTypeface with style : 0
03-20 02:33:52.134 32312-32312/com.example.photo D/TextView: setTypeface with style : 0
03-20 02:33:52.141 32312-32312/com.example.photo D/ViewRootImpl#b05cbf4[MainActivity]: ThreadedRenderer.create() translucent=false
03-20 02:33:52.179 32312-32312/com.example.photo D/InputTransport: Input channel constructed: fd=93
03-20 02:33:52.179 32312-32312/com.example.photo D/ViewRootImpl#b05cbf4[MainActivity]: setView = DecorView#8545f1d[MainActivity] touchMode=true
03-20 02:33:52.183 32312-32312/com.example.photo E/ViewRootImpl: sendUserActionEvent() returned.
03-20 02:33:52.183 32312-32312/com.example.photo D/ViewRootImpl#b05cbf4[MainActivity]: dispatchAttachedToWindow
03-20 02:33:52.210 32312-32312/com.example.photo V/Surface: sf_framedrop debug : 0x4f4c, game : false, logging : 0
03-20 02:33:52.211 32312-32312/com.example.photo D/ViewRootImpl#b05cbf4[MainActivity]: Relayout returned: oldFrame=[0,0][0,0] newFrame=[0,0][2960,1440] result=0x27 surface={isValid=true 548279813120} surfaceGenerationChanged=true
03-20 02:33:52.211 32312-32312/com.example.photo D/ViewRootImpl#b05cbf4[MainActivity]: mHardwareRenderer.initialize() mSurface={isValid=true 548279813120} hwInitialized=true
03-20 02:33:52.220 32312-32312/com.example.photo D/ViewRootImpl#b05cbf4[MainActivity]: MSG_RESIZED_REPORT: frame=Rect(0, 0 - 2960, 1440) ci=Rect(168, 84 - 0, 0) vi=Rect(168, 84 - 0, 0) or=2
03-20 02:33:52.231 32312-32312/com.example.photo D/ViewRootImpl#b05cbf4[MainActivity]: MSG_WINDOW_FOCUS_CHANGED 1
03-20 02:33:52.231 32312-32312/com.example.photo D/ViewRootImpl#b05cbf4[MainActivity]: mHardwareRenderer.initializeIfNeeded()#2 mSurface={isValid=true 548279813120}
03-20 02:33:52.232 32312-32312/com.example.photo V/InputMethodManager: Starting input: tba=android.view.inputmethod.EditorInfo#e558592 nm : com.example.photo ic=null
03-20 02:33:52.232 32312-32312/com.example.photo I/InputMethodManager: startInputInner - mService.startInputOrWindowGainedFocus
03-20 02:33:52.236 32312-32312/com.example.photo D/InputTransport: Input channel constructed: fd=95
03-20 02:33:52.236 32312-32312/com.example.photo D/InputTransport: Input channel destroyed: fd=91
String filename ="content://com.example.photo.fileprovider/external_files/Android/data/com.example.photo/files/Pictures/9999.jpg";
FileInputStream fis= new FileInputStream(filename);
You cannot use a file input stream as you have no file scheme. You have a content scheme. So change to:
InputStream is = getContentResolver().openInputStream(Uri.parse(filename));
And use that stream as you did before.
Instead of this content scheme of your own file provider you could have directly use a file path. As it is you who determined the path or the picture to be taken. You dumped a lot of irrelevant code here and omitted the setup of the used intent.
In your onActivityResult you are trying to get the URI for the file you provided for capturing. So it says that no file found.
Instead try to get the url from Intent received inside the method
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST) {
if (resultCode == RESULT_OK) {
if (data != null) {
photoUri= data.getData();
mImg.setImageURI(photoUri);
Log.i(ApplicationConstant.TAG,"photo_Uri: " + photoUri);
new uploadFileToServerTask().execute(photoUri.toString());
}
}
}
}

Checkbox in the popupMenu

I have popupMenu and CheckBox. I need make write status CheckBox to boolean.
This code not working:
MenuItem fast_result;
boolean fast=false;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.FastResult:
fast_result = item.getSubMenu().getItem(R.id.FastResult);//This is 182 line
fast_result.setChecked(!fast_result.isChecked());
fast=fast_result.isChecked();
return true;
}
}
It is errors:
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.alexvsalex.HelpforMath.RootsActivity.onOptionsItemSelected(RootsActivity.java:182)
at android.app.Activity.onMenuItemSelected(Activity.java:2502)
at com.android.internal.policy.impl.PhoneWindow.onMenuItemSelected(PhoneWindow.java:950)
at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:735)
at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:149)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:874)
at com.android.internal.view.menu.ListMenuPresenter.onItemClick(ListMenuPresenter.java:163)
at android.widget.AdapterView.performItemClick(AdapterView.java:292)
at android.widget.AbsListView.performItemClick(AbsListView.java:1058)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:2514)
at android.widget.AbsListView$1.run(AbsListView.java:3168)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
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:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
What to do?
The problem is solved:
case R.id.FastResult:
fast_result = item; //There was an error
fast_result.setChecked(!fast_result.isChecked());
fast=fast_result.isChecked();
return true;

TextView is not working well

I did this TextView in activity_main.XML that shows a variable. but every time i enter the application its crash.
here is the xml file:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.crosser.MainActivity"
tools:ignore="MergeRootFrame" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Score:"
android:textAppearance="?android:attr/textAppearanceLarge" />
</FrameLayout>
and here is the MainActivity:
TextView myText = (TextView) findViewById(R.id.textView1);
myText.setText("Score:" + result.score);
and here is the Log from logcat
04-01 10:14:01.990: E/AndroidRuntime(925): FATAL EXCEPTION: main
04-01 10:14:01.990: E/AndroidRuntime(925): Process: com.example.crosser, PID: 925
04-01 10:14:01.990: E/AndroidRuntime(925): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.crosser/com.example.crosser.MainActivity}: java.lang.NullPointerException
04-01 10:14:01.990: E/AndroidRuntime(925): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-01 10:14:01.990: E/AndroidRuntime(925): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-01 10:14:01.990: E/AndroidRuntime(925): at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-01 10:14:01.990: E/AndroidRuntime(925): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-01 10:14:01.990: E/AndroidRuntime(925): at android.os.Handler.dispatchMessage(Handler.java:102)
04-01 10:14:01.990: E/AndroidRuntime(925): at android.os.Looper.loop(Looper.java:136)
04-01 10:14:01.990: E/AndroidRuntime(925): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-01 10:14:01.990: E/AndroidRuntime(925): at java.lang.reflect.Method.invokeNative(Native Method)
04-01 10:14:01.990: E/AndroidRuntime(925): at java.lang.reflect.Method.invoke(Method.java:515)
04-01 10:14:01.990: E/AndroidRuntime(925): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-01 10:14:01.990: E/AndroidRuntime(925): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-01 10:14:01.990: E/AndroidRuntime(925): at dalvik.system.NativeStart.main(Native Method)
04-01 10:14:01.990: E/AndroidRuntime(925): Caused by: java.lang.NullPointerException
04-01 10:14:01.990: E/AndroidRuntime(925): at com.example.crosser.MainActivity.onCreate(MainActivity.java:55)
04-01 10:14:01.990: E/AndroidRuntime(925): at android.app.Activity.performCreate(Activity.java:5231)
04-01 10:14:01.990: E/AndroidRuntime(925): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-01 10:14:01.990: E/AndroidRuntime(925): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-01 10:14:01.990: E/AndroidRuntime(925): ... 11 more
Line 55 in Main Activity is that:
myText.setText("Score:" + result.score);
Result is a class that stores the score which is a public variable.
I got this lines that make score be 0 from start and not null.
int score = 0;
Results result = new Results(score);
and this is bassicly the main code in my Main Activity:
Car car = new Car( screenWidth/2 , screenHeigh/2 , 15 , screenHeigh, screenWidth);
Person person = new Person( 0 , screenHeigh/2 , 10 , 20 , screenWidth,screenHeigh);
CarView carview = new CarView(this, car);
PersonView personview = new PersonView(this, person);
GameView gameview = new GameView(this);
gameview.setViews(carview, personview);
setContentView(gameview);
CarMover moveCar = new CarMover(car,gameview);
PersonMover movePerson = new PersonMover(person, gameview, result, car);
Your result variable is probably null, so calling result.score would cause a NullPointerException.
You also need to make sure you call setContentView before using findViewById, otherwise myText may be null.

Geocoder initialization fails

I am getting a NullPointerException when trying to declare the Geocoder in my application. I have the following declaration :
public class MainActivity extends Activity {
private Geocoder geocoder = new Geocoder(this, Locale.getDefault());
...
}
I get the following LogCat :
03-20 10:48:55.729: D/AndroidRuntime(604): Shutting down VM
03-20 10:48:55.729: W/dalvikvm(604): threadid=1: thread exiting with uncaught exception
(group=0x40a71930)
03-20 10:48:56.209: E/AndroidRuntime(604): FATAL EXCEPTION: main
03-20 10:48:56.209: E/AndroidRuntime(604): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.coord/com.example.coord.MainActivity}: java.lang.NullPointerException
03-20 10:48:56.209: E/AndroidRuntime(604): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
03-20 10:48:56.209: E/AndroidRuntime(604): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-20 10:48:56.209: E/AndroidRuntime(604): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-20 10:48:56.209: E/AndroidRuntime(604): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-20 10:48:56.209: E/AndroidRuntime(604): at android.os.Handler.dispatchMessage(Handler.java:99)
03-20 10:48:56.209: E/AndroidRuntime(604): at android.os.Looper.loop(Looper.java:137)
03-20 10:48:56.209: E/AndroidRuntime(604): at android.app.ActivityThread.main(ActivityThread.java:5041)
03-20 10:48:56.209: E/AndroidRuntime(604): at java.lang.reflect.Method.invokeNative(Native Method)
03-20 10:48:56.209: E/AndroidRuntime(604): at java.lang.reflect.Method.invoke(Method.java:511)
03-20 10:48:56.209: E/AndroidRuntime(604): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-20 10:48:56.209: E/AndroidRuntime(604): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-20 10:48:56.209: E/AndroidRuntime(604): at dalvik.system.NativeStart.main(Native Method)
03-20 10:48:56.209: E/AndroidRuntime(604): Caused by: java.lang.NullPointerException
03-20 10:48:56.209: E/AndroidRuntime(604): at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:109)
03-20 10:48:56.209: E/AndroidRuntime(604): at com.example.coord.MainActivity.<init>(MainActivity.java:21)
03-20 10:48:56.209: E/AndroidRuntime(604): at java.lang.Class.newInstanceImpl(Native Method)
03-20 10:48:56.209: E/AndroidRuntime(604): at java.lang.Class.newInstance(Class.java:1319)
03-20 10:48:56.209: E/AndroidRuntime(604): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
03-20 10:48:56.209: E/AndroidRuntime(604): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
Line 21 is my Geocoder declaration. What is wrong with my code?
The context is only available when the activity is started so you cannot initialize the geocoder in the class body. Try to initialize it in the onCreate or onResume method instead...
public class MainActivity extends Activity {
private Geocoder mGeocoder;
#Override
protected void onCreate(Bundle _icicle) {
super.onCreate(_icicle);
mGeocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
}
}
Add this permissions in to manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
and use getApplicationContext() insted of this
It is recommended to use the GeoCode in Background or on separate thread as defined by Google Developers page.
new Thread(new Runnable()
{
#Override
public void run()
{
//Do things.
Geocoder geocoder = new Geocoder(getBaseContext());
try {
// Getting a maximum of 5 Address that matches the input text
addresses = geocoder.getFromLocationName(addressText,5);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();

NullException error in simple loging app

I am making a simple logging system in android. I am following this tutorial. While testing my app I am keep getting NullException error. This error is on this line if(json.getString(KEY_SUCCESS) != null) in LoginScreensActivity below. I have no idea why is json is null. Please help me where am I making mistake.
Here is my code
function which triggers when login button is clicked. This is LoginScreensActivity.java class
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email,password);
try {
if(json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1) {
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Login Screen
finish();
}
} else {
Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
loginUSer function which is triggered in above code
public JSONObject loginUser(String email, String password) {
//Toast.makeText(context, "loginUser function", Toast.LENGTH_LONG).show();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.getJSONFromUrl(loginUrl, params);
//Log.e("JSON", json.toString());
//Log.d("TAG", json.toString());
return json;
}
here is my JSONPareser class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
Log.e("JSON",json);
} catch (Exception e) {
//e.printStackTrace();
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
}
here is my logcat
05-26 20:16:52.658: I/Process(31217): Sending signal. PID: 31217 SIG: 9
05-26 20:16:59.793: D/dalvikvm(31361): GC_EXTERNAL_ALLOC freed 41K, 50% free 2725K/5379K, external 0K/0K, paused 31ms
05-26 20:16:59.843: D/dalvikvm(31361): GC_EXTERNAL_ALLOC freed 7K, 50% free 2743K/5379K, external 455K/518K, paused 32ms
05-26 20:16:59.973: D/CLIPBOARD(31361): Hide Clipboard dialog at Starting input: finished by someone else... !
05-26 20:17:06.883: W/System.err(31361): java.net.UnknownHostException: zafarsaleem.info
05-26 20:17:06.883: W/System.err(31361): at java.net.InetAddress.lookupHostByName(InetAddress.java:506)
05-26 20:17:06.883: W/System.err(31361): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:294)
05-26 20:17:06.883: W/System.err(31361): at java.net.InetAddress.getAllByName(InetAddress.java:256)
05-26 20:17:06.883: W/System.err(31361): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:136)
05-26 20:17:06.883: W/System.err(31361): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
05-26 20:17:06.883: W/System.err(31361): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
05-26 20:17:06.883: W/System.err(31361): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:428)
05-26 20:17:06.883: W/System.err(31361): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-26 20:17:06.888: W/System.err(31361): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-26 20:17:06.888: W/System.err(31361): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
05-26 20:17:06.888: W/System.err(31361): at library.JSONParser.getJSONFromUrl(JSONParser.java:38)
05-26 20:17:06.888: W/System.err(31361): at library.UserFunctions.loginUser(UserFunctions.java:37)
05-26 20:17:06.888: W/System.err(31361): at com.zafar.loginscreens.LoginScreensActivity$1.onClick(LoginScreensActivity.java:48)
05-26 20:17:06.888: W/System.err(31361): at android.view.View.performClick(View.java:2538)
05-26 20:17:06.888: W/System.err(31361): at android.view.View$PerformClick.run(View.java:9152)
05-26 20:17:06.888: W/System.err(31361): at android.os.Handler.handleCallback(Handler.java:587)
05-26 20:17:06.888: W/System.err(31361): at android.os.Handler.dispatchMessage(Handler.java:92)
05-26 20:17:06.888: W/System.err(31361): at android.os.Looper.loop(Looper.java:130)
05-26 20:17:06.888: W/System.err(31361): at android.app.ActivityThread.main(ActivityThread.java:3691)
05-26 20:17:06.888: W/System.err(31361): at java.lang.reflect.Method.invokeNative(Native Method)
05-26 20:17:06.888: W/System.err(31361): at java.lang.reflect.Method.invoke(Method.java:507)
05-26 20:17:06.888: W/System.err(31361): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
05-26 20:17:06.888: W/System.err(31361): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
05-26 20:17:06.888: W/System.err(31361): at dalvik.system.NativeStart.main(Native Method)
05-26 20:17:06.893: E/Buffer Error(31361): Error converting result java.lang.NullPointerException
05-26 20:17:06.893: E/JSON Parser(31361): Error parsing data org.json.JSONException: End of input at character 0 of
05-26 20:17:06.893: D/AndroidRuntime(31361): Shutting down VM
05-26 20:17:06.893: W/dalvikvm(31361): threadid=1: thread exiting with uncaught exception (group=0x4001e578)
05-26 20:17:06.893: E/AndroidRuntime(31361): FATAL EXCEPTION: main
05-26 20:17:06.893: E/AndroidRuntime(31361): java.lang.NullPointerException
05-26 20:17:06.893: E/AndroidRuntime(31361): at com.zafar.loginscreens.LoginScreensActivity$1.onClick(LoginScreensActivity.java:51)
05-26 20:17:06.893: E/AndroidRuntime(31361): at android.view.View.performClick(View.java:2538)
05-26 20:17:06.893: E/AndroidRuntime(31361): at android.view.View$PerformClick.run(View.java:9152)
05-26 20:17:06.893: E/AndroidRuntime(31361): at android.os.Handler.handleCallback(Handler.java:587)
05-26 20:17:06.893: E/AndroidRuntime(31361): at android.os.Handler.dispatchMessage(Handler.java:92)
05-26 20:17:06.893: E/AndroidRuntime(31361): at android.os.Looper.loop(Looper.java:130)
05-26 20:17:06.893: E/AndroidRuntime(31361): at android.app.ActivityThread.main(ActivityThread.java:3691)
05-26 20:17:06.893: E/AndroidRuntime(31361): at java.lang.reflect.Method.invokeNative(Native Method)
05-26 20:17:06.893: E/AndroidRuntime(31361): at java.lang.reflect.Method.invoke(Method.java:507)
05-26 20:17:06.893: E/AndroidRuntime(31361): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
05-26 20:17:06.893: E/AndroidRuntime(31361): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
05-26 20:17:06.893: E/AndroidRuntime(31361): at dalvik.system.NativeStart.main(Native Method)
Update
After adding if(json != null && json.getString(KEY_SUCCESS) != null) { I get following logcat
05-26 20:44:46.243: W/System.err(32680): java.net.UnknownHostException: zafarsaleem.info
05-26 20:44:46.243: W/System.err(32680): at java.net.InetAddress.lookupHostByName(InetAddress.java:506)
05-26 20:44:46.243: W/System.err(32680): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:294)
05-26 20:44:46.243: W/System.err(32680): at java.net.InetAddress.getAllByName(InetAddress.java:256)
05-26 20:44:46.248: W/System.err(32680): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:136)
05-26 20:44:46.248: W/System.err(32680): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
05-26 20:44:46.248: W/System.err(32680): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
05-26 20:44:46.248: W/System.err(32680): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:428)
05-26 20:44:46.248: W/System.err(32680): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-26 20:44:46.248: W/System.err(32680): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-26 20:44:46.248: W/System.err(32680): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
05-26 20:44:46.248: W/System.err(32680): at library.JSONParser.getJSONFromUrl(JSONParser.java:38)
05-26 20:44:46.248: W/System.err(32680): at library.UserFunctions.loginUser(UserFunctions.java:37)
05-26 20:44:46.248: W/System.err(32680): at com.zafar.loginscreens.LoginScreensActivity$1.onClick(LoginScreensActivity.java:49)
05-26 20:44:46.248: W/System.err(32680): at android.view.View.performClick(View.java:2538)
05-26 20:44:46.248: W/System.err(32680): at android.view.View$PerformClick.run(View.java:9152)
05-26 20:44:46.248: W/System.err(32680): at android.os.Handler.handleCallback(Handler.java:587)
05-26 20:44:46.248: W/System.err(32680): at android.os.Handler.dispatchMessage(Handler.java:92)
05-26 20:44:46.248: W/System.err(32680): at android.os.Looper.loop(Looper.java:130)
05-26 20:44:46.248: W/System.err(32680): at android.app.ActivityThread.main(ActivityThread.java:3691)
05-26 20:44:46.248: W/System.err(32680): at java.lang.reflect.Method.invokeNative(Native Method)
05-26 20:44:46.248: W/System.err(32680): at java.lang.reflect.Method.invoke(Method.java:507)
05-26 20:44:46.248: W/System.err(32680): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
05-26 20:44:46.248: W/System.err(32680): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
05-26 20:44:46.248: W/System.err(32680): at dalvik.system.NativeStart.main(Native Method)
05-26 20:44:46.248: E/Buffer Error(32680): Error converting result java.lang.NullPointerException
05-26 20:44:46.248: E/JSON Parser(32680): Error parsing data org.json.JSONException: End of input at character 0 of
The root cause of your trouble is a UnknownHostException, it seems the email EditText doesn't link to a valid URL which returns a null value for json causing the NullPointerException.
What are you entering in email?
Addition
To be explicit, the tutorial code:
if(json.getString(KEY_SUCCESS) != null) {
only checks if the String returned from getString() is not null. In your case json is null so you would need a test like this:
if(json != null && json.getString(KEY_SUCCESS) != null) {
to detect the null pointer and gracefully exit your app.
Addition 2
As the User Functions Class states, if your server is hosted online you need to change these lines of code in your UserFunctions class:
private static String loginURL = "http://10.0.2.2/ah_login_api/";
private static String registerURL = "http://10.0.2.2/ah_login_api/";
If you were Stack Overflow you could try something like:
private static String loginURL = "http://www.stackoverflow.com/ah_login_api/";
private static String registerURL = "http://www.stackoverflow.com/ah_login_api/";
But you are not Stack Overflow, of course, you need to point these URLs to your server and path.

Categories