Why is my app is crashing while using async task? - java

I have used asynctask for the first time. I also used a thread to automatically start a new activity after some time in the same activity.
Android studio shows no error in codes but my app crashes if I login or wait for my new activity to begin.
It is a test app for me using asynctask & connecting with my MySQL.
My code:
public class MainActivity extends AppCompatActivity {
EditText bQ,bR;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread thread=new Thread(){
#Override
public void run() {
try {
sleep(5*1000);
Intent i = new Intent(getApplicationContext(),MainActivity2.class);
startActivity(i);
}
catch (Exception ex)
{}
}
};
thread.start();
ImageView ImageView = (ImageView) findViewById(R.id.imageView);
ImageView.setImageResource(R.drawable.fb);
bQ = (EditText)findViewById(R.id.username);
bR = (EditText)findViewById(R.id.password);
}
public void insertIntoDatabase() {
final String username = bQ.getText().toString();
final String password = bR.getText().toString();
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String paramPassword = params[1];
try {
URL url = new URL("http://passwds.esy.es/upload.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
//OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(httpURLConnection.getOutputStream(), "UTF-8"));
String userPass = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(paramUsername, "UTF-8") + "&"
+ URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(paramPassword, "UTF-8");
bufferedWriter.write(userPass);
bufferedWriter.flush();
bufferedWriter.close();
InputStream inputStream = httpURLConnection.getInputStream();
inputStream.close();
httpURLConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.v("Result:", result);
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(username, password);
}
public void submit(View view) {
insertIntoDatabase();
}
}
LogCat:
04-08 09:54:30.929 6707-6707/? I/art: Late-enabling -Xcheck:jni
04-08 09:54:30.957 6707-6714/? I/art: Debugger is no longer active
04-08 09:54:30.957 6707-6714/? I/art: Starting a blocking GC Instrumentation
04-08 09:54:30.986 6707-6707/? D/LenovoAppIconTheme: ExtraResources;cleanCachedIcon;clear cache..
04-08 09:54:31.145 6707-6707/? W/System: ClassLoader referenced unknown path: /data/app/com.books.admin.foxbooks-1/lib/arm
04-08 09:54:31.159 6707-6707/? I/InstantRun: starting instant run server: is main process
04-08 09:54:31.246 6707-6707/? 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
04-08 09:54:31.297 6707-6707/? V/BoostFramework: mAcquireFunc method = public int com.qualcomm.qti.Performance.perfLockAcquire(int,int[])
04-08 09:54:31.297 6707-6707/? V/BoostFramework: mReleaseFunc method = public int com.qualcomm.qti.Performance.perfLockRelease()
04-08 09:54:31.297 6707-6707/? V/BoostFramework: mAcquireTouchFunc method = public int com.qualcomm.qti.Performance.perfLockAcquireTouch(android.view.MotionEvent,android.util.DisplayMetrics,int,int[])
04-08 09:54:31.297 6707-6707/? V/BoostFramework: mIOPStart method = public int com.qualcomm.qti.Performance.perfIOPrefetchStart(int,java.lang.String)
04-08 09:54:31.298 6707-6707/? V/BoostFramework: mIOPStop method = public int com.qualcomm.qti.Performance.perfIOPrefetchStop()
04-08 09:54:31.300 6707-6707/? V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#cb8650
04-08 09:54:31.300 6707-6707/? V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#b74c049
04-08 09:54:31.529 6707-6727/? I/Adreno: QUALCOMM build : c6f59fa, Ie9c95840c4
Build Date : 06/16/17
OpenGL ES Shader Compiler Version: XE031.09.00.03
Local Branch :
Remote Branch : refs/tags/AU_LINUX_ANDROID_LA.UM.5.5.R1.07.00.00.269.021
Remote Branch : NONE
Reconstruct Branch : NOTHING
04-08 09:54:31.535 6707-6727/? I/OpenGLRenderer: Initialized EGL, version 1.4
04-08 09:54:31.535 6707-6727/? D/OpenGLRenderer: Swap behavior 1
04-08 09:54:31.571 6707-6707/? 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
04-08 09:54:36.623 6707-6707/com.books.admin.foxbooks V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#633747d
04-08 09:54:36.623 6707-6707/com.books.admin.foxbooks V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#714df72
04-08 09:54:36.794 6707-6707/com.books.admin.foxbooks D/AndroidRuntime: Shutting down VM
04-08 09:54:36.795 6707-6707/com.books.admin.foxbooks E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.books.admin.foxbooks, PID: 6707
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.books.admin.foxbooks/com.books.admin.foxbooks.MainActivity2}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
at com.books.admin.foxbooks.MainActivity2.onCreate(MainActivity2.java:21)
at android.app.Activity.performCreate(Activity.java:6705)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 

You are Calling Activity in a Background Thread Thats Why you are getting Error
You Need to Call Like this
Thread thread=new Thread(){
#Override
public void run() {
try {
sleep(5*1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
Intent i = new Intent(getApplicationContext(),MainActivity2.class);
startActivity(i);
}
});
}
catch (Exception ex)
{}
}
};
thread.start();

Related

java.lang.RuntimeException: Unable to resume activity : java.lang.NullPointerException

I am facing issue with my code.I am getting RuntimeException.Kindly please do help me with this.
I'm getting the following error log :
06-17 18:11:32.646 13750-13750/? E/Zygote: v2
06-17 18:11:32.646 13750-13750/? E/Zygote: accessInfo : 0
06-17 18:11:33.226 13750-13750/com.example.cocol.timisoara2021 E/MotionRecognitionManager: mSContextService = android.hardware.scontext.ISContextService$Stub$Proxy#f847827
06-17 18:11:33.226 13750-13750/com.example.cocol.timisoara2021 E/MotionRecognitionManager: motionService = com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy#d2d3ad4
06-17 18:11:33.226 13750-13750/com.example.cocol.timisoara2021 E/MotionRecognitionManager: motionService = com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy#d2d3ad4
06-17 18:11:36.566 13750-14348/com.example.cocol.timisoara2021 E/GooglePlayServicesUtil: The Google Play services resources were not found. Check your project configuration to ensure that the resources are included.
06-17 18:11:36.666 13750-13750/com.example.cocol.timisoara2021 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.cocol.timisoara2021, PID: 13750
java.lang.RuntimeException: Unable to resume activity {com.example.cocol.timisoara2021/com.example.cocol.timisoara2021.Main2Activity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.wikitude.common.orientation.internal.a.a()' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4226)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4328)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3427)
at android.app.ActivityThread.access$1100(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7407)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.wikitude.common.orientation.internal.a.a()' on a null object reference
at com.wikitude.architect.ArchitectView.onResume(ProGuard:818)
at com.example.cocol.timisoara2021.Main2Activity.onResume(Main2Activity.java:59)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1287)
at android.app.Activity.performResume(Activity.java:7015)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4215)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4328) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3427) 
at android.app.ActivityThread.access$1100(ActivityThread.java:229) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:7407) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 
And here is the line 53:architectView.onResume();
And the code:
package com.example.cocol.timisoara2021;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.wikitude.architect.ArchitectStartupConfiguration;
import com.wikitude.architect.ArchitectView;
public class Main2Activity extends AppCompatActivity {
private ArchitectView architectView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
this.architectView = (ArchitectView) this.findViewById(R.id.architectView);
final ArchitectStartupConfiguration config = new ArchitectStartupConfiguration();
config.setLicenseKey("KKvjW60rM1+LoIdIXdMFdqLeXM8rI6uDFqScJycG9rTXI7GHrRdOx9dycHtxv8Ef6Y6jHB/abqr26X6+eqQXyb+ci4ETEEzCQAQFg3h4/+7DhpwYxY3ayzp3jh/+THcSLe2aKZPAvImpV5Ci0Y7yW891E7d+ionYP0iqJJt6mbNTYWx0ZWRfX05DoEhYDMgfmFUvxnY5fbtk7wnaNnJf4Orfhl+Zfp9DmwItjh/lTSX7MTbprDG700m7vZfWqY1j41pA5vYMiBTiiE1vn6qK66jZ8H5nxjsi3Jp3iAynh2VltO95P6CQy5IKBC9HYdWDtvL/lEmWk1lCOhs4xX8kxwsfD1rxqICVD+zP5Uv+4wnug4++E6vFSwUtDgSN+hY38QnTmh6wXKO5aO7PUm20UXC/7k2lvWNwywwX6LMwF4H4ShnIDQDdWSMSuLshIHvR4SWPNN3r+wK5ImnI/fl/yWmkpH66wB5jWSuE6PvIOSIKz+esUzxprAfQxT6bkpenU/jxNwPaYB8ZbhUHCSCN7vWvGO7z12V/B98xWCGzRdZE5VZqNEOyPA/AfvjSJBmenYpvgm4dw0hgyBQrkoc56P6jOEc8W1aSKdfXfmv0olhbapaEzSoKubZXoZ0ZgPPfjQ6eHtzSVkoOB2fHCVONXseHnjsj9+LYNx3w+DLn0PY=");
this.architectView.onCreate(config);
}
protected void OnPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
architectView.onPostCreate();
try {
this.architectView.load("file:///android_asset/POI/index.html");
}catch (Exception e) {
}
}
#Override
protected void onPause() {
super.onPause();
architectView.onPause();
}
#Override
protected void onResume() {
super.onResume();
architectView.onResume();
}
#Override
protected void onDestroy() {
super.onDestroy();
architectView.onDestroy();
}
}
How can I fix this ?
Your onPostCreate method has an uppercase "O". Because of this i assume it is never called which means that the ArchitectView is in an invalid state when you call architectView.onResume.
Try:
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
architectView.onPostCreate();
try {
this.architectView.load("file:///android_asset/POI/index.html");
}catch (Exception e) {
}
}

ListAdapter does not work

I have a mainActivity which has a button named monitoring. When I press the button it should show the nearby beacons. When I press the button an error shows up which say's my application stopped working. Here is the code of the button activity:
public class MonitoringBeacons extends AppCompatActivity {
private ProximityManagerContract proximityManager;
ListAdapter beaconsAdapter;
ListView listView;
List<String> beaconsList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_monitoring_beacons);
KontaktSDK.initialize("kasjdhioasjkdoasdjo");
proximityManager = new ProximityManager(this);
proximityManager.setEddystoneListener(createEddystoneListener());
setAdapter();
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String beacon = String.valueOf(adapterView.getItemAtPosition(position));
Toast.makeText(MonitoringBeacons.this, beacon, Toast.LENGTH_SHORT).show();
}
}
);
}
protected void setAdapter() {
if(beaconsList.isEmpty()) {
Toast.makeText(MonitoringBeacons.this, "No beacons found", Toast.LENGTH_SHORT).show();
return ;
}
beaconsAdapter = new CustomListAdapter(this, beaconsList);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(beaconsAdapter);
}
#Override
protected void onStart() {
super.onStart();
startScanning();
}
#Override
protected void onStop() {
proximityManager.stopScanning();
super.onStop();
}
#Override
protected void onDestroy() {
proximityManager.disconnect();
proximityManager = null;
super.onDestroy();
}
private void startScanning() {
proximityManager.connect(new OnServiceReadyListener() {
#Override
public void onServiceReady() {
proximityManager.startScanning();
}
});
}
private EddystoneListener createEddystoneListener() {
return new SimpleEddystoneListener() {
#Override
public void onEddystoneDiscovered(IEddystoneDevice eddystone, IEddystoneNamespace namespace) {
beaconsList.add(eddystone.getUniqueId());
setAdapter();
}
#Override
public void onEddystoneLost(IEddystoneDevice eddystone, IEddystoneNamespace namespace) {
beaconsList.remove(eddystone.getUniqueId());
setAdapter();
}
};
}
}
and the code of CustomListAdapter:
public class CustomListAdapter extends BaseAdapter {
private List<String> beaconsList;
private Activity activity;
private LayoutInflater inflater;
public CustomListAdapter(Activity activity, List<String> beaconsList) {
this.activity = activity;
this.beaconsList = beaconsList;
}
#Override
public int getCount() {
return beaconsList.size();
}
#Override
public Object getItem(int location) {
return beaconsList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.custom_row, null);
String singleBeaconItem = String.valueOf(getItem(position));
TextView beaconText = (TextView) convertView.findViewById(R.id.BeaconText);
ImageView beaconImage = (ImageView) convertView.findViewById(R.id.BeaconImage);
beaconText.setText(singleBeaconItem);
beaconImage.setImageResource(R.drawable.tough_beacon_1);
return convertView;
}
}
Ideally when I press the button the nearby beacons should be appeared as a list, and when a beacon is discovered or lost the list should automaticaly be updated.
EDITED
Stack trace in LogCat
--------- beginning of crash
08-06 17:02:15.276 2559-2559/com.example.panagiotis.beaconsproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.panagiotis.beaconsproject, PID: 2559
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.panagiotis.beaconsproject/com.example.panagiotis.beaconsproject.MonitoringBeacons}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference
at com.example.panagiotis.beaconsproject.MonitoringBeacons.onCreate(MonitoringBeacons.java:44)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
08-06 17:02:18.087 2559-2559/com.example.panagiotis.beaconsproject I/Process: Sending signal. PID: 2559 SIG: 9
08-06 17:02:22.298 3433-3433/com.example.panagiotis.beaconsproject W/System: ClassLoader referenced unknown path: /data/app/com.example.panagiotis.beaconsproject-1/lib/x86
08-06 17:02:22.455 3433-3433/com.example.panagiotis.beaconsproject W/System: ClassLoader referenced unknown path: /data/app/com.example.panagiotis.beaconsproject-1/lib/x86
08-06 17:02:22.604 3433-3433/com.example.panagiotis.beaconsproject 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
08-06 17:02:22.715 3433-3460/com.example.panagiotis.beaconsproject D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
[ 08-06 17:02:22.718 3433: 3433 D/ ]
HostConnection::get() New Host Connection established 0xaa9a71c0, tid 3433
[ 08-06 17:02:22.754 3433: 3460 D/ ]
HostConnection::get() New Host Connection established 0xaa9a6920, tid 3460
08-06 17:02:22.768 3433-3460/com.example.panagiotis.beaconsproject I/OpenGLRenderer: Initialized EGL, version 1.4
08-06 17:02:24.070 3433-3460/com.example.panagiotis.beaconsproject E/Surface: getSlotFromBufferLocked: unknown buffer: 0xaa9b17f0
08-06 17:02:26.685 3433-3433/com.example.panagiotis.beaconsproject W/ViewRootImpl: Cancelling event due to no window focus: MotionEvent { action=ACTION_CANCEL, actionButton=0, id[0]=0, x[0]=397.5, y[0]=956.6797, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=70853, downTime=67680, deviceId=0, source=0x1002 }
08-06 17:02:26.685 3433-3433/com.example.panagiotis.beaconsproject W/ViewRootImpl: Cancelling event due to no window focus: MotionEvent { action=ACTION_CANCEL, actionButton=0, id[0]=0, x[0]=397.5, y[0]=956.6797, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=70853, downTime=67680, deviceId=0, source=0x1002 }
08-06 17:02:26.686 3433-3433/com.example.panagiotis.beaconsproject W/ViewRootImpl: Cancelling event due to no window focus: MotionEvent { action=ACTION_CANCEL, actionButton=0, id[0]=0, x[0]=397.5, y[0]=956.6797, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=70853, downTime=67680, deviceId=0, source=0x1002 }
08-06 17:02:26.686 3433-3433/com.example.panagiotis.beaconsproject W/ViewRootImpl: Cancelling event due to no window focus: MotionEvent { action=ACTION_CANCEL, actionButton=0, id[0]=0, x[0]=397.5, y[0]=956.6797, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=70853, downTime=67680, deviceId=0, source=0x1002 }
08-06 17:02:28.817 3433-3460/com.example.panagiotis.beaconsproject E/Surface: getSlotFromBufferLocked: unknown buffer: 0xaa9b17f0
08-06 17:02:29.373 3433-3460/com.example.panagiotis.beaconsproject E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb40938f0
08-06 17:02:29.375 3433-3460/com.example.panagiotis.beaconsproject D/OpenGLRenderer: endAllStagingAnimators on 0xa1d53580 (RippleDrawable) with handle 0xa203f910
08-06 17:02:30.806 3433-3460/com.example.panagiotis.beaconsproject E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb4094e60
08-06 17:02:32.811 3433-3460/com.example.panagiotis.beaconsproject E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb40938f0
08-06 17:02:35.874 3433-3433/com.example.panagiotis.beaconsproject D/AndroidRuntime: Shutting down VM
08-06 17:02:35.874 3433-3433/com.example.panagiotis.beaconsproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.panagiotis.beaconsproject, PID: 3433
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.panagiotis.beaconsproject/com.example.panagiotis.beaconsproject.MonitoringBeacons}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setOnItemClickListener(android.widget.AdapterView$OnItemClickListener)' on a null object reference
at com.example.panagiotis.beaconsproject.MonitoringBeacons.onCreate(MonitoringBeacons.java:44)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
08-06 17:02:39.204 3433-3433/com.example.panagiotis.beaconsproject I/Process: Sending signal. PID: 3433 SIG: 9
Any idea?
The stacktrace explains what is happening.
When this line of code executes:
listView.setOnItemClickListener(...
The listView has not yet been initialized, so it is null. This causes a NullPointerException.
That variable is initialized in the setAdapter() method, but it may not be because the method exits early if beaconsList.isEmpty() evaluates to true.
The simple solution is to move the code that initializes listView to top of that method.

Fatal exception at main android during dropbox authentication [duplicate]

This question already exists:
Dropbox Core API is not working. I don't want to hardcode app key and secret?
Closed 7 years ago.
I am getting fatal exception error at main nullpointer exception. basically i have 2 activities login and main activity.you will enter app key and app secret in login activity then after authentication it will take you to main activity any help ??
login activity
public class login_activity extends AppCompatActivity {
public String APP_kEY ;
public String APP_SECRET;
public String accessToken;
EditText app_key_view;
EditText App_secret_view;
Button dropbox;
public DropboxAPI<AndroidAuthSession> mDBApi;
#Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences pref = getSharedPreferences("login",MODE_PRIVATE);
APP_kEY = pref.getString("appkey",null);
APP_SECRET = pref.getString("appsecret",null);
accessToken = pref.getString("access",null);
if (accessToken != null){
AppKeyPair appkeys = new AppKeyPair(APP_kEY,APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appkeys);
session.setOAuth2AccessToken(accessToken);
Intent i = new Intent(login_activity.this,MainActivity.class);
startActivity(i);
finish();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_activity);
app_key_view=(EditText)findViewById(R.id.app_key_text);
App_secret_view=(EditText)findViewById(R.id.app_secret_text);
dropbox = (Button)findViewById(R.id.link_dropbox);
//////////////////////////////////////////////////////////////
dropbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
APP_kEY = app_key_view.getText().toString();
APP_SECRET = App_secret_view.getText().toString();
AppKeyPair appKeys = new AppKeyPair(APP_kEY,APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeys);
mDBApi = new DropboxAPI<>(session);
mDBApi.getSession().startOAuth2Authentication(login_activity.this);
}
});
}
#Override
protected void onResume () {
super.onResume();
if(mDBApi.getSession().authenticationSuccessful()){
try {
mDBApi.getSession().finishAuthentication();
accessToken = mDBApi.getSession().getOAuth2AccessToken();
SharedPreferences.Editor editor = getSharedPreferences("login",MODE_PRIVATE).edit();
editor.putString("appkey",APP_kEY);
editor.putString("appsecret",APP_SECRET);
editor.putString("access",accessToken);
editor.commit();
Intent i = new Intent(login_activity.this,MainActivity.class);
startActivity(i);
finish();
}
catch (IllegalStateException e){
Log.i("DbAuthLog", "Error authenticationg", e);
}
}
}
Logcat
09-11 21:06:01.947 3842-3842/? I/art﹕ Late-enabling -Xcheck:jni
09-11 21:06:01.975 3842-3851/? I/art﹕ Debugger is no longer active
09-11 21:06:02.370 3842-3857/? I/art﹕ Background sticky concurrent mark sweep GC freed 2909(253KB) AllocSpace objects, 2(32KB) LOS objects, 0% free, 50MB/50MB, paused 36.891ms total 133.660ms
09-11 21:06:02.803 3842-3842/? D/AndroidRuntime﹕ Shutting down VM
09-11 21:06:02.803 3842-3842/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.ayzaz.timescopev1.timescope, PID: 3842
java.lang.RuntimeException: Unable to resume activity {com.example.ayzaz.timescopev1.timescope/com.example.ayzaz.timescopev1.timescope.login_activity}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.dropbox.client2.session.Session com.dropbox.client2.DropboxAPI.getSession()' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2986)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3017)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.dropbox.client2.session.Session com.dropbox.client2.DropboxAPI.getSession()' on a null object reference
at com.example.ayzaz.timescopev1.timescope.login_activity.onResume(login_activity.java:77)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1257)
at android.app.Activity.performResume(Activity.java:6076)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2975)
            at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3017)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
09-11 21:06:05.849 3842-3842/com.example.ayzaz.timescopev1.timescope I/Process﹕ Sending signal. PID: 3842 SIG: 9
onResume() always gets called after onCreate().
When onResume() begins, mDBApi is null, because this field is only ever assigned in the onClick() method.
You either need to assign mDBApi in onCreate() directly, or you need to check that it is not null before you try to use it.

Cannot update text in EditText inside onActivityResult

I am trying to use Voice Recognition on Android. Following is my code.
This is the code of the Button that is responsible to start speech recognition.
speak.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "City Name Please?");
startActivityForResult(intent, REQUEST_CODE);
}});
Here is a onActivityResult method.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
ArrayList<String> matches_Text = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Log.v("Results", matches_Text.get(0).toString());
//Update EditText cityname here
String normalized_cityname = matches_Text.get(0).toString().trim();
normalized_cityname = normalized_cityname.replace(" ","%20");
try {
getResponseString("http://api.openweathermap.org/data/2.5/weather?q="+normalized_cityname+"&units=metric", true);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
The code worked ok but there are two problems I am encountering now and I am afraid that they may be related.
If I try to update text in an EditText instance cityname using cityname.setText(matches_Text.get(0).toString()), it crashes the app.
If I hit the speak button now, the google voice dialog comes up but shows can't reacg google at the moment.
Please suggest what can I do?
Adding the getResponseString method also.
public void getResponseString(String Url, boolean IsCalledOnVoiceInput) throws IOException, JSONException {
String temperature="";
String city;
String country;
String weather_main, weather_description;
MyAsyncTask xxx = new MyAsyncTask();
try {
String responseString = xxx.execute(Url).get();
TextView txtTemp = (TextView)findViewById(R.id.txt_temp);
TextView txtCity = (TextView)findViewById(R.id.txt_CityName);
TextView txtWeatherMain = (TextView)findViewById(R.id.textView2);
TextView txtWeatherDescription = (TextView)findViewById(R.id.textView3);
JSONObject reader = new JSONObject(responseString);
JSONObject main = reader.getJSONObject("main");
temperature = main.getString("temp");
Log.v("temperarure",temperature);
city = reader.getString("name");
Log.v("city",city);
JSONObject sys = reader.getJSONObject("sys");
country = sys.getString("country");
Log.v("country",country);
JSONArray weather = reader.getJSONArray("weather");
JSONObject weather_obj = weather.getJSONObject(0);
weather_main = weather_obj.getString("main");
weather_description = weather_obj.getString("description");
txtTemp.setText(temperature+" °C");
txtCity.setText(city+" ("+country+")");
txtWeatherMain.setText(weather_main);
txtWeatherDescription.setText(weather_description);
if(IsCalledOnVoiceInput)
Speak_Weather_Data(city,temperature,weather_main,weather_description);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (JSONException e){
e.printStackTrace();
}
}
Here is the log output
12-24 13:36:06.050 12164-12164/samarth.learning.http D/dalvikvm﹕ Late-enabling CheckJNI
12-24 13:36:06.300 12164-12164/samarth.learning.http D/Network﹕ Network
12-24 13:36:06.300 12164-12164/samarth.learning.http V/Lat﹕ 28.8331443
12-24 13:36:06.300 12164-12164/samarth.learning.http V/Long﹕ 78.7717138
12-24 13:36:06.360 12164-12164/samarth.learning.http D/libEGL﹕ loaded /vendor/lib/egl/libEGL_adreno.so
12-24 13:36:06.370 12164-12164/samarth.learning.http D/libEGL﹕ loaded /vendor/lib/egl/libGLESv1_CM_adreno.so
12-24 13:36:06.380 12164-12164/samarth.learning.http D/libEGL﹕ loaded /vendor/lib/egl/libGLESv2_adreno.so
12-24 13:36:06.380 12164-12164/samarth.learning.http I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:316>: EGL 1.4 QUALCOMM build: (CL4169980)
OpenGL ES Shader Compiler Version: 17.01.10.SPL
Build Date: 11/04/13 Mon
Local Branch:
Remote Branch:
Local Patches:
Reconstruct Branch:
12-24 13:36:06.430 12164-12164/samarth.learning.http D/OpenGLRenderer﹕ Enabling debug mode 0
12-24 13:36:06.531 12164-12164/samarth.learning.http E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
12-24 13:36:06.531 12164-12164/samarth.learning.http E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
12-24 13:36:08.232 12164-12164/samarth.learning.http W/IInputConnectionWrapper﹕ showStatusIcon on inactive InputConnection
12-24 13:36:18.844 12164-12164/samarth.learning.http V/Results﹕ new delhi
12-24 13:36:18.844 12164-12164/samarth.learning.http D/AndroidRuntime﹕ Shutting down VM
12-24 13:36:18.844 12164-12164/samarth.learning.http W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4157c8b0)
12-24 13:36:18.854 12164-12164/samarth.learning.http E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1234, result=-1, data=Intent { (has extras) }} to activity {samarth.learning.http/samarth.learning.http.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3462)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3505)
at android.app.ActivityThread.access$1100(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1346)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:5225)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at samarth.learning.http.MainActivity.onActivityResult(MainActivity.java:160)
at android.app.Activity.dispatchActivityResult(Activity.java:5322)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3458)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3505)
            at android.app.ActivityThread.access$1100(ActivityThread.java:150)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1346)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:213)
            at android.app.ActivityThread.main(ActivityThread.java:5225)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
            at dalvik.system.NativeStart.main(Native Method)
12-24 13:36:22.558 12164-12164/samarth.learning.http I/Process﹕ Sending signal. PID: 12164 SIG: 9
is this what you mean?
i think matches_Text is sometimes NULL?! how about adding an
if(matches_Text == null){
Log.v("Results","matches_Text is NULL!");
return;
}
add above code just after ArrayList<String> matches_Text = da...

Android displaying image from Database

Hi I learned how to grab data from a SQL and display onto TextView. But I'm having little trouble displaying images.
The images are stored in the SQL database as URL but I can't display as an image onto the view.
I've done some research and found on "How to display image with given URL", but I'm just having a little difficulty understanding the concept of grabbing the URL and display .. Please kindly help me. Thank you!
This is the errorLog i'm getting.
Update
Line 159 : photoMe.setImageDrawable(drawable);
11-15 14:53:21.450: W/LoadImageFromWebOperations(28444): java.net.MalformedURLException: Protocol not found: photo
11-15 14:53:21.480: D/AndroidRuntime(28444): Shutting down VM
11-15 14:53:21.480: W/dalvikvm(28444): threadid=1: thread exiting with uncaught exception (group=0x40c55a68)
11-15 14:53:21.500: E/AndroidRuntime(28444): FATAL EXCEPTION: main
11-15 14:53:21.500: E/AndroidRuntime(28444): java.lang.NullPointerException
11-15 14:53:21.500: E/AndroidRuntime(28444): at com.app.android.DirectoryDetailMeActivity$GetDirectoryDetails$1.run(DirectoryDetailMeActivity.java:159)
11-15 14:53:21.500: E/AndroidRuntime(28444): at android.os.Handler.handleCallback(Handler.java:605)
11-15 14:53:21.500: E/AndroidRuntime(28444): at android.os.Handler.dispatchMessage(Handler.java:92)
11-15 14:53:21.500: E/AndroidRuntime(28444): at android.os.Looper.loop(Looper.java:137)
11-15 14:53:21.500: E/AndroidRuntime(28444): at android.app.ActivityThread.main(ActivityThread.java:4517)
11-15 14:53:21.500: E/AndroidRuntime(28444): at java.lang.reflect.Method.invokeNative(Native Method)
11-15 14:53:21.500: E/AndroidRuntime(28444): at java.lang.reflect.Method.invoke(Method.java:511)
11-15 14:53:21.500: E/AndroidRuntime(28444): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
11-15 14:53:21.500: E/AndroidRuntime(28444): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
11-15 14:53:21.500: E/AndroidRuntime(28444): at dalvik.system.NativeStart.main(Native Method)
public class DirectoryDetailMeActivity extends Activity {
ImageView photoMe;
TextView txtName;
String uid;
String photo = "";
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String url_veiw_directory = "directory_detail_me.php";
private static final String TAG_ID = "uid";
private static final String TAG_IMG = "photo";
private static final String TAG_NAME = "name";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.directory_detail_me);
uid = i.getStringExtra(TAG_ID);
new GetDirectoryDetails().execute();
}
class GetDirectoryDetails extends AsyncTask<String, String, String> {
protected String doInBackground(String... params) {
runOnUiThread(new Runnable() {
public void run() {
int success;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", uid));
JSONObject json = jsonParser.makeHttpRequest(url_veiw_directory, "GET", params);
Log.d("my profile", json.toString());
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
JSONArray directoryObj = json.getJSONArray(TAG_DIRECTORY);
JSONObject directory = directoryObj.getJSONObject(0);
txtName.setText(directory.getString(TAG_NAME));
Drawable drawable = LoadImageURL(TAG_IMG);
photoMe.setImageDrawable(drawable);
txtName = (TextView) findViewById(R.id.name);
photoMe = (ImageView) findViewById(R.id.photo);
}else{
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private Drawable LoadImageURL(String url)
{
try
{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "photo");
return d;
}
catch (Exception e)
{
Log.w("LoadImageURL",e.toString());
return null;
}
}
});
return null;
}
}
}
You don't seem to understand an AsyncTask. The point is that it does not run on the UI thread, making it possible to do long term IO like HTTP connections. Wrapping the entire doInBackground in a runOnUIThread is completely counter to that. Its not your only problem, but its on the list.
The rest is too hard to read due to formatting, but look on line 159. Some variable you're using there is null.

Categories

Resources