App crash after image capture from webview - java

try to capture image from webview.Its working fine but in galaxy note 3 operating on android lollipop 5.0 it crashes after clicking select button.
webView.setWebChromeClient(new WebChromeClient() {
// For Android 5.0
public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
//qrCodeReaderView.stopCamera();
mFilePathCallback = filePath;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException e) {
e.printStackTrace();
}
mCapturedImageURI = Uri.fromFile(photoFile);
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI
);
} else {
}
startActivityForResult(takePictureIntent, INPUT_FILE_REQUEST_CODE);
return true;
}
});
Logcat:
11-28 01:00:54.473 D/Activity(13624): performCreate Call secproduct feature valuefalse
11-28 01:00:54.473 D/Activity(13624): performCreate Call debug elastic valuetrue
11-28 01:00:54.473 E/Main (13624): cancel timer
11-28 01:00:54.893 E/Main (13624): Invoking logout timer
11-28 01:00:54.963 E/WindowManager(13624):
11-28 01:00:54.963 E/WindowManager(13624): android.view.WindowLeaked: Activity com.shashank.gaintz.WebViewActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{1de4327 V.E..... R......D 0,0-144,144} that was originally added here
11-28 01:00:54.963 E/WindowManager(13624): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:465)
11-28 01:00:54.963 E/WindowManager(13624): at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:277)
11-28 01:00:54.963 E/WindowManager(13624): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
11-28 01:00:54.963 E/WindowManager(13624): at android.app.Dialog.show(Dialog.java:312)
11-28 01:00:54.963 E/WindowManager(13624): at com.shashank.gaintz.WebViewActivity$2.onPageStarted(WebViewActivity.java:327)
11-28 01:00:54.963 E/WindowManager(13624): at com.android.webview.chromium.WebViewContentsClientAdapter.onPageStarted(WebViewContentsClientAdapter.java:190)
11-28 01:00:54.963 E/WindowManager(13624): at org.chromium.android_webview.AwContentsClientCallbackHelper$MyHandler.handleMessage(AwContentsClientCallbackHelper.java:20)
11-28 01:00:54.963 E/WindowManager(13624): at android.os.Handler.dispatchMessage(Handler.java:102)
11-28 01:00:54.963 E/WindowManager(13624): at android.os.Looper.loop(Looper.java:145)
11-28 01:00:54.963 E/WindowManager(13624): at android.app.ActivityThread.main(ActivityThread.java:5938)
11-28 01:00:54.963 E/WindowManager(13624): at java.lang.reflect.Method.invoke(Native Method)
11-28 01:00:54.963 E/WindowManager(13624): at java.lang.reflect.Method.invoke(Method.java:372)
11-28 01:00:54.963 E/WindowManager(13624): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1389)
11-28 01:00:54.963 E/WindowManager(13624): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1184)
11-28 01:00:55.023 D/Activity(13624): performCreate Call secproduct feature valuefalse
11-28 01:00:55.023 D/Activity(13624): performCreate Call debug elastic valuetrue
11-28 01:00:55.023 E/Main (13624): cancel timer
11-28 01:00:55.133 E/ViewRootImpl(13624): sendUserActionEvent() mView == null
11-28 01:00:55.133 I/Timeline(13624): Timeline: Activity_idle id: android.os.BinderProxy#260d2f13 time:22633932
11-28 01:00:55.133 I/Timeline(13624): Timeline: Activity_idle id: android.os.BinderProxy#260d2f13 time:22633932
11-28 01:00:55.553 D/AndroidRuntime(13624): Shutting down VM
11-28 01:00:55.553 E/ReportHandler(13624): FATAL EXCEPTION: main
11-28 01:00:55.553 E/ReportHandler(13624): java.lang.IllegalArgumentException: View=com.android.internal.policy.impl.PhoneWindow$DecorView{1de4327 V.E..... R......D 0,0-144,144} not attached to window manager
11-28 01:00:55.553 E/ReportHandler(13624): at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:402)
11-28 01:00:55.553 E/ReportHandler(13624): at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:328)
11-28 01:00:55.553 E/ReportHandler(13624): at android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:84)
11-28 01:00:55.553 E/ReportHandler(13624): at android.app.Dialog.dismissDialog(Dialog.java:431)
11-28 01:00:55.553 E/ReportHandler(13624): at android.app.Dialog.dismiss(Dialog.java:414)
11-28 01:00:55.553 E/ReportHandler(13624): at com.shashank.gaintz.WebViewActivity$2.onPageFinished(WebViewActivity.java:307)
11-28 01:00:55.553 E/ReportHandler(13624): at com.android.webview.chromium.WebViewContentsClientAdapter.onPageFinished(WebViewContentsClientAdapter.java:199)
11-28 01:00:55.553 E/ReportHandler(13624): at org.chromium.android_webview.AwContentsClientCallbackHelper$MyHandler.handleMessage(AwContentsClientCallbackHelper.java:72)
11-28 01:00:55.553 E/ReportHandler(13624): at android.os.Handler.dispatchMessage(Handler.java:102)
11-28 01:00:55.553 E/ReportHandler(13624): at android.os.Looper.loop(Looper.java:145)
11-28 01:00:55.553 E/ReportHandler(13624): at android.app.ActivityThread.main(ActivityThread.java:5938)
11-28 01:00:55.553 E/ReportHandler(13624): at java.lang.reflect.Method.invoke(Native Method)
11-28 01:00:55.553 E/ReportHandler(13624): at java.lang.reflect.Method.invoke(Method.java:372)
11-28 01:00:55.553 E/ReportHandler(13624): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1389)
11-28 01:00:55.553 E/ReportHandler(13624): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1184)
11-28 01:00:55.563 I/Timeline(13624): Timeline: Activity_launch_request id:com.shashank.gaintz time:22634360
11-28 01:00:55.633 I/Process (13624): Sending signal. PID: 13624 SIG: 9
11-28 01:00:55.803 E/SELinux (14806): [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
11-28 01:00:55.803 I/art (14806): Late-enabling -Xcheck:jni
11-28 01:00:55.823 D/TimaKeyStoreProvider(14806): TimaSignature is unavailable
11-28 01:00:55.823 D/ActivityThread(14806): Added TimaKeyStore provider
11-28 01:00:55.863 E/SELinux (14823): [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
11-28 01:00:55.863 I/art (14823): Late-enabling -Xcheck:jni
11-28 01:00:55.873 D/ResourcesManager(14806): creating new AssetManager and set to /data/app/com.shashank.gaintz-1/base.apk
11-28 01:00:55.893 D/TimaKeyStoreProvider(14823): TimaSignature is unavailable
11-28 01:00:55.893 D/ActivityThread(14823): Added TimaKeyStore provider

Related

Registration Error! org.json JSONException Value of type java.lang.String cannot be converted to JSONObject

I am new to android programming. I had a problem with the output of Json on the virtual screen. But when I checked my register.php it looks okay because the result is entered into the database but the output of the screen says a different thing- the error it displayed is
Registration Error! org.json JSONException Value of type
java.lang.String cannot be converted to JSONObject.
What am i doing wrong?
This is my java code
RegisterActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
loading = findViewById(R.id.loading);
full_name = findViewById(R.id.full_name);
name = findViewById(R.id.name);
phone = findViewById(R.id.phone);
email = findViewById(R.id.email);
address = findViewById(R.id.address);
sch_name = findViewById(R.id.sch_name);
lga = findViewById(R.id.lga);
password = findViewById(R.id.password);
c_password = findViewById(R.id.c_password);
btn_regist = findViewById(R.id.btn_regist);
btn_regist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Regist();
}
});
}
private void Regist() {
loading.setVisibility(View.VISIBLE);
btn_regist.setVisibility(View.GONE);
final String full_name = this.full_name.getText().toString().trim();
final String name = this.name.getText().toString().trim();
final String phone = this.phone.getText().toString().trim();
final String email = this.email.getText().toString().trim();
final String address = this.address.getText().toString().trim();
final String sch_name = this.sch_name.getText().toString().trim();
final String lga = this.lga.getText().toString().trim();
final String password = this.password.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGIST,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if(success.equals("1")){
Toast.makeText(RegisterActivity.this, "Registration Successful!", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(RegisterActivity.this, "Registration Error! " + e.toString(), Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_regist.setVisibility(View.VISIBLE);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(RegisterActivity.this, "Registration Error! " + error.toString(), Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_regist.setVisibility(View.VISIBLE);
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("full_name",full_name);
params.put("name",name);
params.put("phone",phone);
params.put("email",email);
params.put("address",address);
params.put("sch_name",sch_name);
params.put("lga",lga);
params.put("password",password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
my register.php is
$full_name = $_POST['full_name'];
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$address = $_POST['address'];
$sch_name = $_POST['sch_name'];
$lga = $_POST['lga'];
$password = $_POST['password'];
$password = password_hash($password, PASSWORD_DEFAULT);
require_once 'connect.php';
$sql = "INSERT INTO users_table (full_name,name,phone,email,address,sch_name,lga,password) VALUES ('$full_name', '$name','$phone', '$email', '$address', '$sch_name', '$lga', '$password')";
if(mysqli_query($conn, $sql) ) {
$result["success"] = "1";
$result["message"] = "success";
json_encode($result);
mysqli_close($conn);
}else{
$result["success"] = "0";
$result["message"] = "error";
json_encode($result);
mysqli_close($conn);
}
}
?>
This is the Logcat Code
11-28 11:07:25.168 3258-3258/? E/libprocessgroup: failed to make and chown /acct/uid_10061: Read-only file system
11-28 11:07:25.168 3258-3258/? W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
11-28 11:07:25.168 3258-3258/? I/art: Not late-enabling -Xcheck:jni (already on)
11-28 11:07:25.194 3258-3266/? E/art: Failed writing handshake bytes (-1 of 14): Broken pipe
11-28 11:07:25.194 3258-3266/? I/art: Debugger is no longer active
11-28 11:07:25.323 3258-3258/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.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
11-28 11:07:25.421 3258-3258/? I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
11-28 11:07:25.423 3258-3258/? I/art: Rejecting re-init on previously-failed class java.lang.Class<androidx.core.view.ViewCompat$2>
11-28 11:07:25.616 3258-3258/? I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
11-28 11:07:25.627 3258-3258/? I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
11-28 11:07:25.657 3258-3278/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
11-28 11:07:25.661 3258-3258/? D/Atlas: Validating map...
11-28 11:07:25.713 3258-3278/? I/OpenGLRenderer: Initialized EGL, version 1.4
11-28 11:07:25.714 3258-3278/? W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
11-28 11:07:29.625 3258-3278/com.cdscomputer.registerlogin D/EGL_emulation: eglCreateContext: 0xae834b80: maj 2 min 0 rcv 2
11-28 11:07:29.637 3258-3278/com.cdscomputer.registerlogin D/EGL_emulation: eglMakeCurrent: 0xae834b80: ver 2 0 (tinfo 0xae839380)
11-28 11:07:29.650 3258-3278/com.cdscomputer.registerlogin D/OpenGLRenderer: Enabling debug mode 0
11-28 11:07:29.685 3258-3278/com.cdscomputer.registerlogin D/EGL_emulation: eglMakeCurrent: 0xae834b80: ver 2 0 (tinfo 0xae839380)
11-28 11:07:29.747 3258-3258/com.cdscomputer.registerlogin I/Choreographer: Skipped 243 frames! The application may be doing too much work on its main thread.
11-28 11:07:37.488 3258-3258/com.cdscomputer.registerlogin I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
11-28 11:07:37.495 3258-3258/com.cdscomputer.registerlogin I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
11-28 11:07:37.502 3258-3258/com.cdscomputer.registerlogin I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
11-28 11:07:37.518 3258-3258/com.cdscomputer.registerlogin I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
11-28 11:07:37.531 3258-3258/com.cdscomputer.registerlogin I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
11-28 11:07:37.545 3258-3258/com.cdscomputer.registerlogin I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
11-28 11:07:37.559 3258-3258/com.cdscomputer.registerlogin I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
11-28 11:07:37.574 3258-3258/com.cdscomputer.registerlogin I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
11-28 11:07:37.597 3258-3258/com.cdscomputer.registerlogin I/TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead.
11-28 11:07:37.670 3258-3278/com.cdscomputer.registerlogin D/EGL_emulation: eglMakeCurrent: 0xae834b80: ver 2 0 (tinfo 0xae839380)
11-28 11:07:38.074 3258-3278/com.cdscomputer.registerlogin D/EGL_emulation: eglMakeCurrent: 0xae834b80: ver 2 0 (tinfo 0xae839380)
11-28 11:07:42.407 3258-3258/com.cdscomputer.registerlogin I/Choreographer: Skipped 260 frames! The application may be doing too much work on its main thread.
11-28 11:07:42.435 3258-3278/com.cdscomputer.registerlogin D/EGL_emulation: eglMakeCurrent: 0xae834b80: ver 2 0 (tinfo 0xae839380)
11-28 11:07:54.461 3258-3258/com.cdscomputer.registerlogin W/System.err: org.json.JSONException: Value < of type java.lang.String cannot be converted to JSONObject
11-28 11:07:54.461 3258-3258/com.cdscomputer.registerlogin W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
11-28 11:07:54.462 3258-3258/com.cdscomputer.registerlogin W/System.err: at org.json.JSONObject.<init>(JSONObject.java:160)
11-28 11:07:54.463 3258-3258/com.cdscomputer.registerlogin W/System.err: at org.json.JSONObject.<init>(JSONObject.java:173)
11-28 11:07:54.463 3258-3258/com.cdscomputer.registerlogin W/System.err: at com.cdscomputer.registerlogin.RegisterActivity$2.onResponse(RegisterActivity.java:82)
11-28 11:07:54.463 3258-3258/com.cdscomputer.registerlogin W/System.err: at com.cdscomputer.registerlogin.RegisterActivity$2.onResponse(RegisterActivity.java:76)
11-28 11:07:54.463 3258-3258/com.cdscomputer.registerlogin W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:82)
11-28 11:07:54.463 3258-3258/com.cdscomputer.registerlogin W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:29)
11-28 11:07:54.463 3258-3258/com.cdscomputer.registerlogin W/System.err: at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
11-28 11:07:54.463 3258-3258/com.cdscomputer.registerlogin W/System.err: at android.os.Handler.handleCallback(Handler.java:739)
11-28 11:07:54.463 3258-3258/com.cdscomputer.registerlogin W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
11-28 11:07:54.463 3258-3258/com.cdscomputer.registerlogin W/System.err: at android.os.Looper.loop(Looper.java:135)
11-28 11:07:54.463 3258-3258/com.cdscomputer.registerlogin W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5254)
11-28 11:07:54.463 3258-3258/com.cdscomputer.registerlogin W/System.err: at java.lang.reflect.Method.invoke(Native Method)
11-28 11:07:54.463 3258-3258/com.cdscomputer.registerlogin W/System.err: at java.lang.reflect.Method.invoke(Method.java:372)
11-28 11:07:54.463 3258-3258/com.cdscomputer.registerlogin W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
11-28 11:07:54.463 3258-3258/com.cdscomputer.registerlogin W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
11-28 11:07:54.557 3258-3278/com.cdscomputer.registerlogin D/EGL_emulation: eglMakeCurrent: 0xae834b80: ver 2 0 (tinfo 0xae839380)
11-28 11:07:54.579 3258-3278/com.cdscomputer.registerlogin V/RenderScript: 0xb41ad000 Launching thread(s), CPUs 2
11-28 11:07:55.005 3258-3278/com.cdscomputer.registerlogin D/EGL_emulation: eglMakeCurrent: 0xae834b80: ver 2 0 (tinfo 0xae839380)
11-28 11:07:56.487 3258-3278/com.cdscomputer.registerlogin D/EGL_emulation: eglMakeCurrent: 0xae834b80: ver 2 0 (tinfo 0xae839380)
it works but not the right way if i change this
if(success.equals("1")){
Toast.makeText(RegisterActivity.this, "Registration Successful!", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(RegisterActivity.this, //Change this code to the below code-> "Registration Error! " + e.toString(), Toast.LENGTH_SHORT).show(); ->to
"Registration Successful!", Toast.LENGTH_SHORT).show();
}
}
},

Error in performing bluetooth file transfer in android

I created an app for Transfer of file from bluetooth in android but unfortunately my app crashes
Following is my main source code and log of error.I have a file named "hi.txt" in my sdcard.
Kindly guide where i a going wrong.
public class MainActivity extends AppCompatActivity
{
ListView listViewPaired;
ListView listViewDetected;
ArrayList<String> arrayListpaired;
Button buttonSearch, buttonOn, buttonDesc, buttonOff;
ArrayAdapter<String> adapter, detectedAdapter, mNewDevicesArrayAdapter;
static HandleSeacrh handleSeacrh;
BluetoothDevice bdDevice;
BluetoothClass bdClass;
ArrayList<BluetoothDevice> arrayListPairedBluetoothDevices;
private ButtonClicked clicked;
ListItemClickedonPaired listItemClickedonPaired;
BluetoothAdapter bluetoothAdapter = null;
ArrayList<BluetoothDevice> arrayListBluetoothDevices = null;
ListItemClicked listItemClicked;
UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listViewDetected = (ListView) findViewById(R.id.listViewDetected);
listViewPaired = (ListView) findViewById(R.id.listViewPaired);
buttonSearch = (Button) findViewById(R.id.buttonSearch);
buttonOn = (Button) findViewById(R.id.buttonOn);
buttonDesc = (Button) findViewById(R.id.buttonDesc);
buttonOff = (Button) findViewById(R.id.buttonOff);
arrayListpaired = new ArrayList<String>();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
clicked = new ButtonClicked();
handleSeacrh = new HandleSeacrh();
arrayListPairedBluetoothDevices = new ArrayList<BluetoothDevice>();
/*
* the above declaration is just for getting the paired bluetooth devices;
* this helps in the removing the bond between paired devices.
*/
listItemClickedonPaired = new ListItemClickedonPaired();
arrayListBluetoothDevices = new ArrayList<BluetoothDevice>();
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, arrayListpaired);
detectedAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_single_choice);
mNewDevicesArrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_single_choice);
listViewDetected.setAdapter(detectedAdapter);
listItemClicked = new ListItemClicked();
detectedAdapter.notifyDataSetChanged();
listViewPaired.setAdapter(adapter);
}
#Override
protected void onStart()
{
// TODO Auto-generated method stub
super.onStart();
getPairedDevices();
buttonOn.setOnClickListener(clicked);
buttonSearch.setOnClickListener(clicked);
buttonDesc.setOnClickListener(clicked);
buttonOff.setOnClickListener(clicked);
listViewDetected.setOnItemClickListener(listItemClicked);
listViewPaired.setOnItemClickListener(listItemClickedonPaired);
}
private void getPairedDevices()
{
Set<BluetoothDevice> pairedDevice = bluetoothAdapter.getBondedDevices();
if (pairedDevice.size() > 0)
{
for (BluetoothDevice device : pairedDevice)
{
arrayListpaired.add(device.getName() + "\n" + device.getAddress());
arrayListPairedBluetoothDevices.add(device);
}
}
adapter.notifyDataSetChanged();
}
class ListItemClicked implements AdapterView.OnItemClickListener
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
bdDevice = arrayListBluetoothDevices.get(position);
Log.i("Log", "The dvice : " + bdDevice.toString());
Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if (isBonded) {
Log.i("Log", "Paired");
}
} catch (Exception e)
{
e.printStackTrace();
}
Log.i("Log", "The bond is created: " + isBonded);
}
}
public void btSend()
{
String path = Environment.getExternalStorageDirectory()+"/hi.txt";
File file = new File(path);
BluetoothSocket socket= null;
try
{
socket = bdDevice.createRfcommSocketToServiceRecord(applicationUUID);
socket.connect();
}
catch (IOException e)
{
e.printStackTrace();
}
ContentValues values = new ContentValues();
values.put(BluetoothShare.URI, path);
values.put(BluetoothShare.DESTINATION,bdDevice.getAddress());
values.put(BluetoothShare.DIRECTION, BluetoothShare.DIRECTION_OUTBOUND);
Long ts = System.currentTimeMillis();
values.put(BluetoothShare.TIMESTAMP, ts);
getContentResolver().insert(BluetoothShare.CONTENT_URI,values);
}
class ListItemClickedonPaired implements AdapterView.OnItemClickListener
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bdDevice = arrayListPairedBluetoothDevices.get(position);
try {
Boolean removeBond = removeBond(bdDevice);
if (removeBond) {
arrayListpaired.remove(position);
adapter.notifyDataSetChanged();
}
Log.i("Log", "Removed" + removeBond);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private Boolean connect(BluetoothDevice bdDevice)
{
Boolean bool = false;
try {
Log.i("Log", "service method is called ");
Class cl = Class.forName("android.bluetooth.BluetoothDevice");
Class[] par = {};
Method method = cl.getMethod("createBond", par);
Object[] args = {};
bool = (Boolean) method.invoke(bdDevice);//, args);
} catch (Exception e)
{
Log.i("Log", "Inside catch of serviceFromDevice Method");
e.printStackTrace();
}
return bool.booleanValue();
};
public boolean removeBond(BluetoothDevice btDevice) throws Exception
{
Class btClass = Class.forName("android.bluetooth.BluetoothDevice");
Method removeBond = btClass.getMethod("removeBond");
Boolean returnValue = (Boolean)removeBond.invoke(btDevice);
return returnValue.booleanValue();
}
public boolean createBond(BluetoothDevice btDevice)
throws Exception
{
Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
Method createBondMethod = class1.getMethod("createBond");
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
class ButtonClicked implements View.OnClickListener
{
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.buttonOn:
onBluetooth();
break;
case R.id.buttonSearch:
arrayListBluetoothDevices.clear();
startSearching();
break;
case R.id.buttonDesc:
makeDiscoverable();
break;
case R.id.buttonOff:
offBluetooth();
break;
default:
break;
}
}
}
private BroadcastReceiver myReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent) {
Message msg = Message.obtain();
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
Toast.makeText(context, "ACTION_FOUND", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Searching for devices", Toast.LENGTH_LONG).show();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
try {
//device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
//device.getClass().getMethod("cancelPairingUserInput", boolean.class).invoke(device);
} catch (Exception e) {
Log.i("Log", "Inside the exception: ");
e.printStackTrace();
}
if (arrayListBluetoothDevices.size() < 1) // this checks if the size of bluetooth device is 0,then add the
{ // device to the arraylist.
detectedAdapter.add(device.getName() + "\n" + device.getAddress());
arrayListBluetoothDevices.add(device);
detectedAdapter.notifyDataSetChanged();
} else {
boolean flag = true; // flag to indicate that particular device is already in the arlist or not
for (int i = 0; i < arrayListBluetoothDevices.size(); i++) {
if (device.getAddress().equals(arrayListBluetoothDevices.get(i).getAddress())) {
flag = false;
}
}
if (flag == true) {
detectedAdapter.add(device.getName() + "\n" + device.getAddress());
arrayListBluetoothDevices.add(device);
detectedAdapter.notifyDataSetChanged();
}
}
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
arrayListBluetoothDevices.add(device);
}
}
}
};
private void startSearching()
{
Log.i("Log", "in the start searching method");
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
MainActivity.this.registerReceiver(myReceiver, intentFilter);
bluetoothAdapter.startDiscovery();
}
private void onBluetooth()
{
if (!bluetoothAdapter.isEnabled()) {
bluetoothAdapter.enable();
Log.i("Log", "Bluetooth is Enabled");
Toast.makeText(getApplicationContext(), "Turned on", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Already on", Toast.LENGTH_LONG).show();
}
}
private void offBluetooth()
{
if (bluetoothAdapter.isEnabled())
{
bluetoothAdapter.disable();
Toast.makeText(getApplicationContext(), "Turned off", Toast.LENGTH_LONG).show();
}
}
private void makeDiscoverable()
{
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
Log.i("Log", "Discoverable ");
}
class HandleSeacrh extends Handler
{
#Override
public void handleMessage(Message msg) {
switch (msg.what)
{
case 111:
break;
default:
break;
}
}
}
}
Log file:
13170-13170/com.example.toshiba.bluetoothdemo D/ActivityThread: handleBindApplication:com.example.toshiba.bluetoothdemo
11-16 18:01:45.587 13170-13170/com.example.toshiba.bluetoothdemo D/ActivityThread: setTargetHeapUtilization:0.75
11-16 18:01:45.587 13170-13170/com.example.toshiba.bluetoothdemo D/ActivityThread: setTargetHeapMinFree:2097152
11-16 18:01:45.637 13170-13170/com.example.toshiba.bluetoothdemo W/dalvikvm: VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;)
11-16 18:01:45.637 13170-13170/com.example.toshiba.bluetoothdemo I/dalvikvm: Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.internal.view.WindowCallbackWrapper.onSearchRequested
11-16 18:01:45.637 13170-13170/com.example.toshiba.bluetoothdemo W/dalvikvm: VFY: unable to resolve interface method 17915: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z
11-16 18:01:45.637 13170-13170/com.example.toshiba.bluetoothdemo D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
11-16 18:01:45.637 13170-13170/com.example.toshiba.bluetoothdemo I/dalvikvm: Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.internal.view.WindowCallbackWrapper.onWindowStartingActionMode
11-16 18:01:45.637 13170-13170/com.example.toshiba.bluetoothdemo W/dalvikvm: VFY: unable to resolve interface method 17919: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
11-16 18:01:45.637 13170-13170/com.example.toshiba.bluetoothdemo D/dalvikvm: VFY: replacing opcode 0x72 at 0x0002
11-16 18:01:45.637 13170-13170/com.example.toshiba.bluetoothdemo D/dalvikvm: GetMethodID: not returning static method Landroid/os/Process;.getTotalMemory ()J
11-16 18:01:45.647 13170-13170/com.example.toshiba.bluetoothdemo D/dalvikvm: GetMethodID: not returning static method Landroid/os/Process;.getFreeMemory ()J
11-16 18:01:45.687 13170-13170/com.example.toshiba.bluetoothdemo I/dalvikvm: Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
11-16 18:01:45.687 13170-13170/com.example.toshiba.bluetoothdemo W/dalvikvm: VFY: unable to resolve virtual method 439: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
11-16 18:01:45.687 13170-13170/com.example.toshiba.bluetoothdemo D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
11-16 18:01:45.687 13170-13170/com.example.toshiba.bluetoothdemo I/dalvikvm: Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
11-16 18:01:45.687 13170-13170/com.example.toshiba.bluetoothdemo W/dalvikvm: VFY: unable to resolve virtual method 461: Landroid/content/res/TypedArray;.getType (I)I
11-16 18:01:45.687 13170-13170/com.example.toshiba.bluetoothdemo D/dalvikvm: VFY: replacing opcode 0x6e at 0x0002
11-16 18:01:45.787 13170-13170/com.example.toshiba.bluetoothdemo D/BluetoothAdapter: 1112941536: getState() : mService = null. Returning STATE_OFF
11-16 18:01:45.837 13170-13170/com.example.toshiba.bluetoothdemo I/Adreno-EGL: <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: ()
11-16 18:01:45.837 13170-13170/com.example.toshiba.bluetoothdemo I/Adreno-EGL: OpenGL ES Shader Compiler Version: E031.24.02.07
11-16 18:01:45.837 13170-13170/com.example.toshiba.bluetoothdemo I/Adreno-EGL: Build Date: 03/30/15 Mon
11-16 18:01:45.837 13170-13170/com.example.toshiba.bluetoothdemo I/Adreno-EGL: Local Branch:
11-16 18:01:45.837 13170-13170/com.example.toshiba.bluetoothdemo I/Adreno-EGL: Remote Branch:
11-16 18:01:45.837 13170-13170/com.example.toshiba.bluetoothdemo I/Adreno-EGL: Local Patches:
11-16 18:01:45.837 13170-13170/com.example.toshiba.bluetoothdemo I/Adreno-EGL: Reconstruct Branch:
11-16 18:01:45.897 13170-13170/com.example.toshiba.bluetoothdemo D/OpenGLRenderer: Enabling debug mode 0
11-16 18:01:46.037 13170-13170/com.example.toshiba.bluetoothdemo I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#424fa760 time:8721552
11-16 18:01:48.687 13170-13170/com.example.toshiba.bluetoothdemo I/Log: Bluetooth is Enabled
11-16 18:01:48.717 13170-13170/com.example.toshiba.bluetoothdemo W/Toast: From com.example.toshiba.bluetoothdemo, go ahead.
11-16 18:01:50.267 13170-13170/com.example.toshiba.bluetoothdemo I/Timeline: Timeline: Activity_launch_request time:8725789
11-16 18:01:50.297 13170-13170/com.example.toshiba.bluetoothdemo I/Log: Discoverable
11-16 18:01:52.337 13170-13170/com.example.toshiba.bluetoothdemo I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#424fa760 time:8727857
11-16 18:01:53.227 13170-13170/com.example.toshiba.bluetoothdemo I/Log: in the start searching method
11-16 18:01:54.717 13170-13170/com.example.toshiba.bluetoothdemo W/Toast: From com.example.toshiba.bluetoothdemo, go ahead.
11-16 18:01:54.727 13170-13170/com.example.toshiba.bluetoothdemo W/Toast: From com.example.toshiba.bluetoothdemo, go ahead.
11-16 18:01:57.917 13170-13170/com.example.toshiba.bluetoothdemo I/Log: The dvice : 24:EC:99:5C:FA:8C
11-16 18:01:57.947 13170-13170/com.example.toshiba.bluetoothdemo I/Log: The bond is created: false
11-16 18:01:57.957 13170-13170/com.example.toshiba.bluetoothdemo W/BluetoothAdapter: getBluetoothService() called with no BluetoothManagerCallback
11-16 18:01:57.967 13170-13170/com.example.toshiba.bluetoothdemo D/BluetoothSocket: connect(), SocketState: INIT, mPfd: {ParcelFileDescriptor: FileDescriptor[67]}
11-16 18:01:58.567 13567-13567/? W/: [ColorAdjust] gammamode=2, cemode=10
11-16 18:01:58.567 13567-13567/? W/: [ColorAdjust] temp_gammavalue=2, temp_cevalue=10
11-16 18:01:58.567 13567-13567/? W/: [ColorAdjust] Don't setGamma!
11-16 18:01:58.567 13567-13567/? W/: [ColorAdjust] Don't setCe!
11-16 18:01:58.567 13567-13567/? W/: [ColorAdjust] Set temp_prefer temp_ce!
11-16 18:02:02.277 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: java.io.IOException: read failed, socket might closed or timeout, read ret: -1
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:574)
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:585)
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:326)
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at com.example.toshiba.bluetoothdemo.MainActivity.btSend(MainActivity.java:163)
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at com.example.toshiba.bluetoothdemo.MainActivity$ListItemClicked.onItemClick(MainActivity.java:146)
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at android.widget.AdapterView.performItemClick(AdapterView.java:299)
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at android.widget.AbsListView.performItemClick(AbsListView.java:1115)
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at android.widget.AbsListView$PerformClick.run(AbsListView.java:2928)
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at android.widget.AbsListView$3.run(AbsListView.java:3691)
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at android.os.Handler.handleCallback(Handler.java:733)
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at android.os.Looper.loop(Looper.java:136)
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5113)
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
11-16 18:02:02.287 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at java.lang.reflect.Method.invoke(Method.java:515)
11-16 18:02:02.297 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-16 18:02:02.297 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
11-16 18:02:02.297 13170-13170/com.example.toshiba.bluetoothdemo W/System.err: at dalvik.system.NativeStart.main(Native Method)
11-16 18:02:02.307 13170-13170/com.example.toshiba.bluetoothdemo D/AndroidRuntime: Shutting down VM
11-16 18:02:02.307 13170-13170/com.example.toshiba.bluetoothdemo W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x416d9d58)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: FATAL EXCEPTION: main
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: Process: com.example.toshiba.bluetoothdemo, PID: 13170
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: java.lang.SecurityException: Permission Denial: writing com.android.bluetooth.opp.BluetoothOppProvider uri content://com.android.bluetooth.opp/btopp from pid=13170, uid=10137 requires android.permission.ACCESS_BLUETOOTH_SHARE, or grantUriPermission()
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at android.os.Parcel.readException(Parcel.java:1472)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:185)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:137)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at android.content.ContentProviderProxy.insert(ContentProviderNative.java:468)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at android.content.ContentResolver.insert(ContentResolver.java:1190)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at com.example.toshiba.bluetoothdemo.MainActivity.btSend(MainActivity.java:178)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at com.example.toshiba.bluetoothdemo.MainActivity$ListItemClicked.onItemClick(MainActivity.java:146)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at android.widget.AdapterView.performItemClick(AdapterView.java:299)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at android.widget.AbsListView.performItemClick(AbsListView.java:1115)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at android.widget.AbsListView$PerformClick.run(AbsListView.java:2928)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at android.widget.AbsListView$3.run(AbsListView.java:3691)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:733)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:95)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at android.os.Looper.loop(Looper.java:136)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5113)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:515)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
11-16 18:02:02.317 13170-13170/com.example.toshiba.bluetoothdemo E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
'
Read this line in logcat
java.lang.SecurityException: Permission Denial: writing com.android.bluetooth.opp.BluetoothOppProvider uri content://com.android.bluetooth.opp/btopp from pid=13170, uid=10137 requires android.permission.ACCESS_BLUETOOTH_SHARE, or grantUriPermission()
This is your issue, add the android.permission.ACCESS_BLUETOOTH_SHARE permission to your manifest
I should add that this might not be your only error but it is the one causing this specific crash

How to check if checkbox was checked?

I am creating a quiz app for androids. I have 3 fragments and 3 checkboxes on first two of them. On the last fragment there is a button which when pressed opens an activity called "End". I need that on the "End" activity a result would appear of how many correct answers one have chosen.
Firstly, I've tried to check if it's working with only the first fragment, but I got stuck. The app closes when I press the button.
End.java:
package bandymas.viewpagerexample;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
public class End extends ActionBarActivity {
private CheckBox checkBox1, checkBox2, checkBox3;
private Button button;
TextView newresult = (TextView)findViewById(R.id.textView1);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_end);
getSupportActionBar().hide();
addListenerOnButton();
}
private void addListenerOnButton() {
checkBox1 = (CheckBox) findViewById(R.id.checkBox1);
checkBox2 = (CheckBox) findViewById(R.id.checkBox2);
checkBox3 = (CheckBox) findViewById(R.id.checkBox3);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
//Run when button is clicked
#Override
public void onClick(View v) {
StringBuffer result = new StringBuffer();
result.append("CheckBox1 : ").append(checkBox1.isChecked());
result.append("\nCheckbox2 : ").append(checkBox2.isChecked());
result.append("\nCheckBox3 :").append(checkBox3.isChecked());
newresult.setText("My Awesome Text");
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_naujas_baigimas, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here's my logcat:
04-01 20:04:37.564 6020-6020/bandymas.viewpagerexample W/ApplicationPackageManager﹕ getCSCPackageItemText()
04-01 20:04:37.564 6020-6020/bandymas.viewpagerexample I/PersonaManager﹕ getPersonaService() name persona_policy
04-01 20:04:37.684 6020-6020/bandymas.viewpagerexample I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:381>: EGL 1.4 QUALCOMM build: (CL3869936)
OpenGL ES Shader Compiler Version: 17.01.11.SPL
Build Date: 01/17/14 Fri
Local Branch:
Remote Branch:
Local Patches:
Reconstruct Branch:
04-01 20:04:37.734 6020-6020/bandymas.viewpagerexample D/OpenGLRenderer﹕ Enabling debug mode 0
04-01 20:07:31.404 7094-7094/bandymas.viewpagerexample I/SELinux﹕ Function: selinux_android_load_priority [0], There is no sepolicy file.
04-01 20:07:31.404 7094-7094/bandymas.viewpagerexample I/SELinux﹕ Function: selinux_android_load_priority , priority version is VE=SEPF_GT-I9505_4.4.2_0033
04-01 20:07:31.404 7094-7094/bandymas.viewpagerexample I/SELinux﹕ selinux_android_seapp_context_reload: seapp_contexts file is loaded from /seapp_contexts
04-01 20:07:31.404 7094-7094/bandymas.viewpagerexample E/dalvikvm﹕ >>>>> Normal User
04-01 20:07:31.404 7094-7094/bandymas.viewpagerexample E/dalvikvm﹕ >>>>> bandymas.viewpagerexample [ userId:0 | appId:10229 ]
04-01 20:07:31.404 7094-7094/bandymas.viewpagerexample D/dalvikvm﹕ Late-enabling CheckJNI
04-01 20:07:31.584 7094-7094/bandymas.viewpagerexample W/ApplicationPackageManager﹕ getCSCPackageItemText()
04-01 20:07:31.594 7094-7094/bandymas.viewpagerexample I/PersonaManager﹕ getPersonaService() name persona_policy
04-01 20:07:31.794 7094-7094/bandymas.viewpagerexample I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:381>: EGL 1.4 QUALCOMM build: (CL3869936)
OpenGL ES Shader Compiler Version: 17.01.11.SPL
Build Date: 01/17/14 Fri
Local Branch:
Remote Branch:
Local Patches:
Reconstruct Branch:
04-01 20:07:31.844 7094-7094/bandymas.viewpagerexample D/OpenGLRenderer﹕ Enabling debug mode 0
04-01 20:07:42.454 7094-7094/bandymas.viewpagerexample W/ApplicationPackageManager﹕ getCSCPackageItemText()
04-01 20:07:42.485 7094-7094/bandymas.viewpagerexample I/dalvikvm﹕ Could not find method android.view.ViewGroup.onNestedScrollAccepted, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.onNestedScrollAccepted
04-01 20:07:42.485 7094-7094/bandymas.viewpagerexample W/dalvikvm﹕ VFY: unable to resolve virtual method 11347: Landroid/view/ViewGroup;.onNestedScrollAccepted (Landroid/view/View;Landroid/view/View;I)V
04-01 20:07:42.485 7094-7094/bandymas.viewpagerexample D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0000
04-01 20:07:42.485 7094-7094/bandymas.viewpagerexample I/dalvikvm﹕ Could not find method android.view.ViewGroup.onStopNestedScroll, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.onStopNestedScroll
04-01 20:07:42.485 7094-7094/bandymas.viewpagerexample W/dalvikvm﹕ VFY: unable to resolve virtual method 11353: Landroid/view/ViewGroup;.onStopNestedScroll (Landroid/view/View;)V
04-01 20:07:42.485 7094-7094/bandymas.viewpagerexample D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0000
04-01 20:07:42.485 7094-7094/bandymas.viewpagerexample I/dalvikvm﹕ Could not find method android.support.v7.internal.widget.ActionBarOverlayLayout.stopNestedScroll, referenced from method android.support.v7.internal.widget.ActionBarOverlayLayout.setHideOnContentScrollEnabled
04-01 20:07:42.485 7094-7094/bandymas.viewpagerexample W/dalvikvm﹕ VFY: unable to resolve virtual method 9041: Landroid/support/v7/internal/widget/ActionBarOverlayLayout;.stopNestedScroll ()V
04-01 20:07:42.485 7094-7094/bandymas.viewpagerexample D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x000e
04-01 20:07:42.495 7094-7094/bandymas.viewpagerexample I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
04-01 20:07:42.495 7094-7094/bandymas.viewpagerexample W/dalvikvm﹕ VFY: unable to resolve virtual method 365: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
04-01 20:07:42.495 7094-7094/bandymas.viewpagerexample D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
04-01 20:07:42.495 7094-7094/bandymas.viewpagerexample I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
04-01 20:07:42.495 7094-7094/bandymas.viewpagerexample W/dalvikvm﹕ VFY: unable to resolve virtual method 387: Landroid/content/res/TypedArray;.getType (I)I
04-01 20:07:42.495 7094-7094/bandymas.viewpagerexample D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002
04-01 20:07:42.525 7094-7094/bandymas.viewpagerexample D/AndroidRuntime﹕ Shutting down VM
04-01 20:07:42.525 7094-7094/bandymas.viewpagerexample W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4187fda0)
04-01 20:07:42.525 7094-7094/bandymas.viewpagerexample E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: bandymas.viewpagerexample, PID: 7094
java.lang.RuntimeException: Unable to start activity ComponentInfo{bandymas.viewpagerexample/bandymas.viewpagerexample.End}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
at android.app.ActivityThread.access$900(ActivityThread.java:161)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
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:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at bandymas.viewpagerexample.End.addListenerOnButton(End.java:33)
at bandymas.viewpagerexample.End.onCreate(End.java:23)
at android.app.Activity.performCreate(Activity.java:5426)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
            at android.app.ActivityThread.access$900(ActivityThread.java:161)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5356)
            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:1265)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
            at dalvik.system.NativeStart.main(Native Method)
activity_end.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="bandymas.viewpagerexample.End">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Result"
android:id="#+id/textView1"
android:layout_marginTop="100dp"
android:textSize="40dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Please Check that there is the button(R.id.button) in activity_end.xml.
I guess that the button's id doesn't exist in activity_end.xml.

java.lang.runtimeexception unable to start activity componentinfo java.lang.nullpointerexception android

im making a simple calories calculator and it gives me that error, i already reviewed the code and searched here for the solution but im not able to see why is not running.
I thought it was because i had not initialized the variable, so i did it and still got the same error, maybe is something with the spinners, im new on using spinners
here is the code:
public class CaloriesCalculator extends ActionBarActivity {
EditText etAge, etWeight, etHeight;
Button btnCalculate;
TextView tvResult;
Spinner spinnerGender, spinnerActivity;
String itemGender, itemActivity;
int Height=0;
int Weight=0;
int Age=0;;
double bmr=0.0;
double tdee=0.0;
String result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.caloriescalculator);
spinnerGender=(Spinner)findViewById(R.id.spinnerGender);
spinnerActivity=(Spinner)findViewById(R.id.spinnerActivity);
etAge=(EditText)findViewById(R.id.etAge);
etWeight=(EditText)findViewById(R.id.etWeight);
etHeight=(EditText)findViewById(R.id.etHeight);
tvResult=(TextView)findViewById(R.id.tvResult);
List<String> list = new ArrayList<String>();
list.add("Male");
list.add("Female");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, list );
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerGender.setAdapter(dataAdapter);
List<String> list2 = new ArrayList<String>();
list.add("Sedentary");
list.add("Lightly Active");
list.add("Moderalety Active");
list.add("Very Active");
list.add("Extremely Active");
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, list2 );
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerActivity.setAdapter(dataAdapter2);
btnCalculate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
spinnerGender.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
spinnerActivity.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int position, long id) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
itemGender=String.valueOf(spinnerGender.getSelectedItem());
itemActivity=String.valueOf(spinnerActivity.getSelectedItem());
if(itemGender=="Male"){
Weight=Integer.parseInt(etWeight.getText().toString());
Height=Integer.parseInt(etHeight.getText().toString());
Age=Integer.parseInt(etAge.getText().toString());
if(itemActivity=="Sedentary"){
bmr=66+((13.7 * Weight)+(5*Height))-(6.8*Age);
tdee=bmr*1.2;
}
else if(itemActivity=="Lightly Active"){
bmr=66+((13.7 * Weight)+(5*Height))-(6.8*Age);
tdee=bmr*1.375;
}
else if(itemActivity=="Moderalety Active"){
bmr=66+((13.7 * Weight)+(5*Height))-(6.8*Age);
tdee=bmr*1.55;
}
else if(itemActivity=="Very Active"){
bmr=66+((13.7 * Weight)+(5*Height))-(6.8*Age);
tdee=bmr*1.725;
}
else if(itemActivity=="Extremely Active"){
bmr=66+((13.7 * Weight)+(5*Height))-(6.8*Age);
tdee=bmr*1.9;
}
}
else if(itemGender=="Female") {
Weight=Integer.parseInt(etWeight.getText().toString());
Height=Integer.parseInt(etHeight.getText().toString());
Age=Integer.parseInt(etAge.getText().toString());
if(itemActivity=="Sedentary"){
bmr=655+((9.6*Weight)+(1.8*Height))-(4.7*Age);
tdee=bmr*1.2;
}
else if(itemActivity=="Lightly Active"){
bmr=655+((9.6*Weight)+(1.8*Height))-(4.7*Age);
tdee=bmr*1.375;
}
else if(itemActivity=="Moderalety Active"){
bmr=655+((9.6*Weight)+(1.8*Height))-(4.7*Age);
tdee=bmr*1.55;
}
else if(itemActivity=="Very Active"){
bmr=655+((9.6*Weight)+(1.8*Height))-(4.7*Age);
tdee=bmr*1.725;
}
else if(itemActivity=="Extremely Active"){
bmr=655+((9.6*Weight)+(1.8*Height))-(4.7*Age);
tdee=bmr*1.9;
}
}
result=Double.toString(tdee);
tvResult.setText(result);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
logcat:
11-28 17:20:05.501: E/AndroidRuntime(1455): FATAL EXCEPTION: main
11-28 17:20:05.501: E/AndroidRuntime(1455): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.calculadoracalorias/com.app.calculadoracalorias.CaloriesCalculator}: java.lang.NullPointerException
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.os.Handler.dispatchMessage(Handler.java:99)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.os.Looper.loop(Looper.java:137)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-28 17:20:05.501: E/AndroidRuntime(1455): at java.lang.reflect.Method.invokeNative(Native Method)
11-28 17:20:05.501: E/AndroidRuntime(1455): at java.lang.reflect.Method.invoke(Method.java:525)
11-28 17:20:05.501: E/AndroidRuntime(1455): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-28 17:20:05.501: E/AndroidRuntime(1455): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-28 17:20:05.501: E/AndroidRuntime(1455): at dalvik.system.NativeStart.main(Native Method)
11-28 17:20:05.501: E/AndroidRuntime(1455): Caused by: java.lang.NullPointerException
11-28 17:20:05.501: E/AndroidRuntime(1455): at com.app.calculadoracalorias.CaloriesCalculator.onCreate(CaloriesCalculator.java:67)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.Activity.performCreate(Activity.java:5133)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-28 17:20:05.501: E/AndroidRuntime(1455): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-28 17:20:05.501: E/AndroidRuntime(1455): ... 11 more
11-28 17:24:42.341: D/AndroidRuntime(1507): Shutting down VM
11-28 17:24:42.341: W/dalvikvm(1507): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-28 17:24:42.371: E/AndroidRuntime(1507): FATAL EXCEPTION: main
11-28 17:24:42.371: E/AndroidRuntime(1507): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.app.calculadoracalorias/com.app.calculadoracalorias.CaloriesCalculator}: java.lang.NullPointerException
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.os.Handler.dispatchMessage(Handler.java:99)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.os.Looper.loop(Looper.java:137)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-28 17:24:42.371: E/AndroidRuntime(1507): at java.lang.reflect.Method.invokeNative(Native Method)
11-28 17:24:42.371: E/AndroidRuntime(1507): at java.lang.reflect.Method.invoke(Method.java:525)
11-28 17:24:42.371: E/AndroidRuntime(1507): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-28 17:24:42.371: E/AndroidRuntime(1507): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-28 17:24:42.371: E/AndroidRuntime(1507): at dalvik.system.NativeStart.main(Native Method)
11-28 17:24:42.371: E/AndroidRuntime(1507): Caused by: java.lang.NullPointerException
11-28 17:24:42.371: E/AndroidRuntime(1507): at com.app.calculadoracalorias.CaloriesCalculator.onCreate(CaloriesCalculator.java:70)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.Activity.performCreate(Activity.java:5133)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-28 17:24:42.371: E/AndroidRuntime(1507): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-28 17:24:42.371: E/AndroidRuntime(1507): ... 11 more
Yout btnCalculate is null, you should initialize before doing the onclickListener:
btnCalculate = (Button)findViewById(R.id.btnCalculate); //your id
Also note that you are initializing the dataAdapter2 but actually you are using dataAdapert, and list2 dont have any elements, because you declare it but u are filling always list1

Android - NullPointerException on ListView adapter when using SimpleDateFormat

I'm having trouble when displaying a custom ListView on a tab (fragment). If I just set the adapter (which is a separate class that extends BaseAdapter) and the fields downloaded from the server, it works just fine. If I set the application to use my custom DateFormat class and format the date taken from the server in dd/MM/aaaa, I get a NullPointerException related to "childMeasure" (full logcat of the error below).
IndicatorsListAdapter.java (the adapter for the ListView)
package android.palharini.myhealth.fragments.tabs.adapters;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.palharini.myhealth.R;
import android.palharini.myhealth.date_time.DateFormat;
import android.palharini.myhealth.db.entities.Indicator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class IndicatorsListAdapter extends BaseAdapter {
static class ViewHolder {
public TextView tvMeasure;
public TextView tvUnit;
public TextView tvDate;
public TextView tvTime;
public int position;
}
private ViewHolder holder;
private Context context;
private Indicator indicator;
private List<Indicator> lsIndicators;
private DateFormat df;
public IndicatorsListAdapter(Context context, List<Indicator> lsIndicators) {
this.context = context;
this.lsIndicators = lsIndicators;
}
#Override
public int getCount() {
return lsIndicators.size();
}
#Override
public Object getItem(int id) {
return lsIndicators.get(id);
}
#Override
public long getItemId(int id) {
return lsIndicators.get(id).getId();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(R.layout.list_indicators, parent, false);
holder = new ViewHolder();
holder.tvMeasure = (TextView) convertView.findViewById(R.id.lvTvMeasure);
holder.tvUnit = (TextView) convertView.findViewById(R.id.lvTvUnit);
holder.tvDate = (TextView) convertView.findViewById(R.id.lvTvDate);
holder.tvTime = (TextView) convertView.findViewById(R.id.lvTvTime);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
indicator = lsIndicators.get(position);
if (indicator != null) {
holder.tvMeasure.setText(indicator.getMedida1().toString());
holder.tvUnit.setText(indicator.getUnidade());
String stDate = df.getDataAndroid(indicator.getData());
holder.tvDate.setText(stDate);
holder.tvTime.setText(indicator.getHora());
}
return convertView;
}
}
WeekTab.java (a tab which has to display the ListView, along with an AndroidPlot graph)
package android.palharini.myhealth.fragments.tabs;
import java.util.Arrays;
import java.util.List;
import com.androidplot.ui.SizeLayoutType;
import com.androidplot.ui.SizeMetrics;
import com.androidplot.xy.LineAndPointFormatter;
import com.androidplot.xy.PointLabelFormatter;
import com.androidplot.xy.SimpleXYSeries;
import com.androidplot.xy.XYPlot;
import com.androidplot.xy.XYSeries;
import com.androidplot.xy.XYStepMode;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.palharini.myhealth.R;
import android.palharini.myhealth.activities.edit.IndicatorEdit;
import android.palharini.myhealth.activities.register.IndicatorRegister;
import android.palharini.myhealth.date_time.DateFormat;
import android.palharini.myhealth.db.dao.IndicatorDAO;
import android.palharini.myhealth.db.entities.Indicator;
import android.palharini.myhealth.fragments.tabs.adapters.IndicatorsListAdapter;
import android.palharini.myhealth.session.SessionManager;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
public class WeekTab extends Fragment {
private static Integer difData = 7;
private static String periodo = "DAY";
private SessionManager sessao;
private DateFormat ts;
private IndicatorDAO indDAO;
private ListView lvIndicadores;
private Button btCadastrarInd;
private Integer intTipoIndicador;
private int x, y=0;
private String stDataBusca;
private Double dbMedia, vtMedias1[], vtMedias2[];
private Integer intIdUsuario, vtDatas[];
private List<Indicator> lsIndicators;
private IndicatorsListAdapter adIndicators;
private XYPlot grafico;
private XYSeries grafSerie1, grafSerie2;
private LineAndPointFormatter grafFormat;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_tab, container, false);
sessao = new SessionManager(getActivity());
ts = new DateFormat();
indDAO = new IndicatorDAO();
lvIndicadores = (ListView) view.findViewById(R.id.listViewInd);
btCadastrarInd = (Button) view.findViewById(R.id.btCadastrarInd);
grafico = (XYPlot) view.findViewById(R.id.xyPlot);
grafico.getBackgroundPaint().setColor(Color.WHITE);
grafico.getGraphWidget().getBackgroundPaint().setColor(Color.WHITE);
grafico.getGraphWidget().getGridBackgroundPaint().setColor(Color.WHITE);
grafico.setDomainStep(XYStepMode.INCREMENT_BY_VAL, 1);
grafico.setPlotMargins(0, 0, 0, 0);
grafico.setPlotPadding(25, 10, 20, 0);
grafico.setGridPadding(30, 30, 30, 10);
grafico.getGraphWidget().setSize(new SizeMetrics(0, SizeLayoutType.FILL, 0, SizeLayoutType.FILL));
grafico.getLayoutManager().remove(grafico.getLegendWidget());
grafico.getLayoutManager().remove(grafico.getDomainLabelWidget());
grafico.getLayoutManager().remove(grafico.getRangeLabelWidget());
grafico.getLayoutManager().remove(grafico.getTitleWidget());
grafico.getLayoutManager().getPaddingPaint().setColor(Color.TRANSPARENT);
grafico.setTicksPerRangeLabel(5);
grafico.setTicksPerDomainLabel(1);
grafico.getGraphWidget().setMarginBottom(15);
Intent intent = getActivity().getIntent();
intTipoIndicador = intent.getIntExtra("tipoSelecionado", 0);
intIdUsuario = sessao.getIdUsuario();
stDataBusca = ts.getDataAtualBusca();
vtMedias1 = new Double[difData+1];
vtMedias2 = new Double[difData+1];
vtDatas = new Integer[difData+1];
for (x = difData; x>=0; x--) {
dbMedia = indDAO.buscarMedia1Periodo(
intTipoIndicador, intIdUsuario, periodo, stDataBusca, x);
if (dbMedia > 0) {
vtMedias1[x] = dbMedia;
vtDatas[x] = x;
y = x;
}
else {
vtMedias1[x] = vtMedias1[y];
vtDatas[x] = x;
}
}
grafSerie1 = new SimpleXYSeries (Arrays.asList(vtDatas), Arrays.asList(vtMedias1), "Médias");
grafFormat = new LineAndPointFormatter(
Color.RED,
Color.RED,
Color.TRANSPARENT,
null);
grafFormat.setPointLabelFormatter(new PointLabelFormatter());
grafFormat.configure(getActivity(), R.xml.formato_serie_medias);
grafico.addSeries(grafSerie1, grafFormat);
if (intTipoIndicador == 3) {
for (int x = difData; x>=0; x--) {
dbMedia = indDAO.buscarMedia2Periodo(
intTipoIndicador, intIdUsuario, periodo, stDataBusca, x);
if (dbMedia > 0) {
vtMedias2[x] = dbMedia;
vtDatas[x] = x;
y = x;
}
else {
vtMedias2[x] = vtMedias2[y];
vtDatas[x] = x;
}
}
grafSerie2 = new SimpleXYSeries (Arrays.asList(vtDatas), Arrays.asList(vtMedias2), "Médias");
grafico.addSeries(grafSerie2, grafFormat);
}
lsIndicators = indDAO.buscarIndicadoresPeriodoTipo(
intIdUsuario, intTipoIndicador, periodo, stDataBusca, difData);
adIndicators = new IndicatorsListAdapter(getActivity(), lsIndicators);
lvIndicadores.setAdapter(adIndicators);
lvIndicadores.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg3) {
// TODO Auto-generated method stub
Indicator indicSelecionado = new Indicator();
indicSelecionado = (Indicator) lvIndicadores.getItemAtPosition(position);
Intent irTelaEdicaoIndicador = new Intent(getActivity(), IndicatorEdit.class);
irTelaEdicaoIndicador.putExtra("idIndicador", indicSelecionado.getId());
startActivity(irTelaEdicaoIndicador);
}
});
btCadastrarInd.setOnClickListener(new Button.OnClickListener () {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent irTelaCadIndicador = new Intent(getActivity(), IndicatorRegister.class);
irTelaCadIndicador.putExtra("tipoSelecionado", intTipoIndicador);
startActivity(irTelaCadIndicador);
}
});
return view;
}
}
Logcat
11-28 13:14:17.177: E/AndroidRuntime(1152): FATAL EXCEPTION: main
11-28 13:14:17.177: E/AndroidRuntime(1152): Process: android.palharini.myhealth, PID: 1152
11-28 13:14:17.177: E/AndroidRuntime(1152): java.lang.NullPointerException
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.palharini.myhealth.fragments.tabs.adapters.IndicatorsListAdapter.getView(IndicatorsListAdapter.java:81)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.widget.AbsListView.obtainView(AbsListView.java:2255)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.widget.ListView.measureHeightOfChildren(ListView.java:1263)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.widget.ListView.onMeasure(ListView.java:1175)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.view.View.measure(View.java:16497)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.view.View.measure(View.java:16497)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.widget.LinearLayout.measureVertical(LinearLayout.java:847)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.view.View.measure(View.java:16497)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.view.View.measure(View.java:16497)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1456)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.view.View.measure(View.java:16497)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.view.View.measure(View.java:16497)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
11-28 13:14:17.177: E/AndroidRuntime(1152): at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:327)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.view.View.measure(View.java:16497)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
11-28 13:14:17.177: E/AndroidRuntime(1152): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.view.View.measure(View.java:16497)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1912)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1109)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1291)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:996)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5600)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.view.Choreographer.doCallbacks(Choreographer.java:574)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.view.Choreographer.doFrame(Choreographer.java:544)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.os.Handler.handleCallback(Handler.java:733)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.os.Handler.dispatchMessage(Handler.java:95)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.os.Looper.loop(Looper.java:136)
11-28 13:14:17.177: E/AndroidRuntime(1152): at android.app.ActivityThread.main(ActivityThread.java:5001)
11-28 13:14:17.177: E/AndroidRuntime(1152): at java.lang.reflect.Method.invokeNative(Native Method)
11-28 13:14:17.177: E/AndroidRuntime(1152): at java.lang.reflect.Method.invoke(Method.java:515)
11-28 13:14:17.177: E/AndroidRuntime(1152): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
11-28 13:14:17.177: E/AndroidRuntime(1152): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
11-28 13:14:17.177: E/AndroidRuntime(1152): at dalvik.system.NativeStart.main(Native Method)
Can someone help me on this? (if additional code samples are needed, I'll be glad to provide)
Thanks in advance!
change
private DateFormat df;
to
private DateFormat df = new SimpleDateFormat("MM-dd kk:mm:ss");
I see private DateFormat df; at the top of your IndicatorsListAdapter-class, but I don't see you intialize it anywhere before you get in the getView line 81:
String stDate = df.getDataAndroid(indicator.getData());
Perhaps change it to:
if(df != null)
String stDate = df.getDataAndroid(indicator.getData());
or simply set your df somewhere before this, like directly at the variable:
private final DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
// replace dd-MM-yyyy with your desired Date format

Categories