These are the classes which I have made
logcat
11-09 11:34:49.183 27661-27661/? I/art: Late-enabling -Xcheck:jni
11-09 11:34:49.193 27661-27661/? D/TidaProvider: TidaProvider()
11-09 11:34:49.197 27661-27661/? V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#ce504
11-09 11:34:49.348 27661-27661/nischayvaish.com.test1 W/System: ClassLoader referenced unknown path: /data/app/nischayvaish.com.test1-1/lib/arm64
11-09 11:34:49.360 27661-27661/nischayvaish.com.test1 I/InstantRun: starting instant run server: is main process
11-09 11:34:49.463 27661-27661/nischayvaish.com.test1 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
11-09 11:34:49.484 27661-27661/nischayvaish.com.test1 D/AccessibilityManager: current package=nischayvaish.com.test1, accessibility manager mIsFinalEnabled=false, mOptimizeEnabled=true, mIsUiAutomationEnabled=false, mIsInterestedPackage=false
11-09 11:34:49.512 27661-27661/nischayvaish.com.test1 V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#d00846
11-09 11:34:49.512 27661-27661/nischayvaish.com.test1 V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#73d0a07
11-09 11:34:49.593 27661-27661/nischayvaish.com.test1 V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#ed682f7
11-09 11:34:49.593 27661-27661/nischayvaish.com.test1 V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#f473564
11-09 11:34:49.647 27661-27661/nischayvaish.com.test1 E/HAL: PATH3 /odm/lib64/hw/gralloc.qcom.so
11-09 11:34:49.647 27661-27661/nischayvaish.com.test1 E/HAL: PATH2 /vendor/lib64/hw/gralloc.qcom.so
11-09 11:34:49.647 27661-27661/nischayvaish.com.test1 E/HAL: PATH1 /system/lib64/hw/gralloc.qcom.so
11-09 11:34:49.647 27661-27661/nischayvaish.com.test1 E/HAL: PATH3 /odm/lib64/hw/gralloc.msm8953.so
11-09 11:34:49.647 27661-27661/nischayvaish.com.test1 E/HAL: PATH2 /vendor/lib64/hw/gralloc.msm8953.so
11-09 11:34:49.647 27661-27661/nischayvaish.com.test1 E/HAL: PATH1 /system/lib64/hw/gralloc.msm8953.so
11-09 11:34:49.654 27661-27661/nischayvaish.com.test1 D/ActivityThreadInjector: clearCachedDrawables.
11-09 11:34:49.673 27661-27691/nischayvaish.com.test1 I/Adreno: QUALCOMM build : 01d2d27, I3d52eaf367
Build Date : 12/10/16
OpenGL ES Shader Compiler Version: XE031.09.00.03
Local Branch :
Remote Branch :
Remote Branch :
Reconstruct Branch :
11-09 11:34:49.679 27661-27691/nischayvaish.com.test1 I/OpenGLRenderer: Initialized EGL, version 1.4
11-09 11:34:49.679 27661-27691/nischayvaish.com.test1 D/OpenGLRenderer: Swap behavior 1
11-09 11:34:49.706 27661-27661/nischayvaish.com.test1 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
This is my mainactivity class
public class MainActivity extends AppCompatActivity {
private TextView tv1;
private RecyclerView recycler_view;
private RecyclerView.LayoutManager layoutManager;
private ArrayList<IncomingNumber> arrayList = new ArrayList<>();
private RecyclerAdapter adapter;
private BroadcastReceiver broadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 = (TextView) findViewById(R.id.emptyTxt);
recycler_view = (RecyclerView) findViewById(R.id.recyclerView);
layoutManager = new LinearLayoutManager(this);
adapter = new RecyclerAdapter(arrayList);
recycler_view.setLayoutManager(layoutManager);
recycler_view.setHasFixedSize(true);
recycler_view.setAdapter(adapter);
readFromDb();
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
readFromDb();
}
};
}
private void readFromDb() {
arrayList.clear();
DbHelper dbHelper = new DbHelper(this);
SQLiteDatabase database = dbHelper.getWritableDatabase();
Cursor cursor = dbHelper.readNumber(database);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String number;
int id;
number = cursor.getString(cursor.getColumnIndex(DbContract.INCOMING_NUMBER));
id = cursor.getInt(cursor.getColumnIndex("id"));
arrayList.add(new IncomingNumber(id, number));
}
cursor.close();
dbHelper.close();
adapter.notifyDataSetChanged();
recycler_view.setVisibility(View.VISIBLE);
tv1.setVisibility(View.GONE);
}
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver, new IntentFilter(DbContract.UPDATE_UI_FILTER));
unregisterReceiver(broadcastReceiver);
}
DbHelper.class
private static final String DATABASE_NAME = "numberDb";
private static final int DATABASE_VERSION = 2;
private static final String CREATE = "CREATE TABLE " + DbContract.TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT," + DbContract.INCOMING_NUMBER + " TEXT);";
private static final String DROP_TABLE = "drop table if exists " + DbContract.TABLE_NAME;
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_TABLE);
onCreate(db);
}
public void saveNumber(String number, SQLiteDatabase database) {
ContentValues contentValues = new ContentValues();
contentValues.put(DbContract.INCOMING_NUMBER, number);
database.insert(DbContract.TABLE_NAME, null, contentValues);
}
public Cursor readNumber(SQLiteDatabase database) {
String[] projection = {"id", DbContract.INCOMING_NUMBER};
return (database.query(DbContract.TABLE_NAME, projection, null, null, null, null, null));
}
On compiling code ,it compiled but it does not show any incoming call number.
currently I am beginner in Android So I did not understand the error properly.
Warning given by the application at the compile time,
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
Phone permission is allowed.
can't write comment because my reputation but try to Toast array size after readFromDb() and Toast adapter count and recyclerview childCount to check if it really add the data to adapter and recyclerview or not
and try to delete recycler_view.setHasFixedSize(true); and let me know if it work or not
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am a beginner at android studio, I have a mission to redesign the app. I use the Fragment. But when I run my app, it has stopped and there is no error in my Gradle. I looked for many website to solve my question, but still have no idea.
I have some questions below.
How can I fix the java.lang.RuntimeException (NULL Pointer Exception) ?
09-30 02:59:56.574 17706-17706/? E/memtrack: Couldn't load memtrack module (No such file or directory)
09-30 02:59:56.574 17706-17706/? E/android.os.Debug: failed to load memtrack module: -2
09-30 02:59:56.996 17722-17722/? E/memtrack: Couldn't load memtrack module (No such file or directory)
09-30 02:59:56.996 17722-17722/? E/android.os.Debug: failed to load memtrack module: -2
09-30 02:59:57.090 17734-17734/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: tw.com.flag.parking22, PID: 17734
java.lang.RuntimeException: Unable to start activity ComponentInfo{tw.com.flag.parking22/tw.com.flag.parking22.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
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 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at tw.com.flag.parking22.MainActivity.init(MainActivity.java:102)
at tw.com.flag.parking22.MainActivity.onCreate(MainActivity.java:71)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
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-30 02:59:57.211 1160-1160/? E/EGL_emulation: tid 1160: eglCreateSyncKHR(1865): error 0x3004 (EGL_BAD_ATTRIBUTE)
09-30 03:02:15.409 2159-19872/com.google.android.gms E/Herrevad: [350] RemoteReportsRefreshChimeraService.a: want to send authenticated request, but no Google account on device
09-30 03:02:15.445 1998-2721/com.google.android.gms.persistent E/SQLiteLog: (2067) abort at 31 in [INSERT INTO pending_ops(source,tag,requires_charging,target_package,source_version,required_network_type,flex_time,target_class,runtime,retry_strategy,last_runtime,period,task_type,job_id,user_
09-30 03:02:15.445 1998-2721/com.google.android.gms.persistent E/SQLiteDatabase: Error inserting source=4 tag=NetworkReportService requires_charging=0 target_package=com.google.android.gms source_version=11509000 required_network_type=2 flex_time=3600000 target_class=com.google.android.gms.common.stats.net.NetworkReportService runtime=1506742923454 retry_strategy={"maximum_backoff_seconds":{"3600":0},"initial_backoff_seconds":{"30":0},"retry_policy":{"0":0}} last_runtime=0 period=7200000 task_type=1 job_id=-1 user_id=0
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: pending_ops.tag, pending_ops.target_class, pending_ops.target_package, pending_ops.user_id (code 2067)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at swi.a(:com.google.android.gms#11509280:208)
at sxo.a(:com.google.android.gms#11509280:64)
at sxp.handleMessage(:com.google.android.gms#11509280:29)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
09-30 03:02:15.446 1998-2721/com.google.android.gms.persistent E/NetworkScheduler: Error persisting task: com.google.android.gms/.common.stats.net.NetworkReportService{u=0 tag="NetworkReportService" trigger=window{period=7200s,flex=3600s,earliest=5988s,latest=9588s} requirements=[NET_ANY] attributes=[PERSISTED,RECURRING] scheduled=2388s last_run=N/A jid=N/A status=PENDING retries=0}
09-30 03:02:15.474 1170-1578/? E/Drm: Failed to find drm plugin
09-30 03:02:15.563 2159-2680/com.google.android.gms E/Volley: [129] BasicNetwork.performRequest: Unexpected response code 307 for https://android.googleapis.com/nova/herrevad/network_quality_info
09-30 03:02:15.888 1998-2721/com.google.android.gms.persistent E/SQLiteLog: (2067) abort at 31 in [INSERT INTO pending_ops(source,tag,requires_charging,target_package,source_version,required_network_type,flex_time,target_class,runtime,retry_strategy,last_runtime,period,task_type,job_id,user_
09-30 03:02:15.888 1998-2721/com.google.android.gms.persistent E/SQLiteDatabase: Error inserting source=4 tag=AggregationTaskTag requires_charging=0 target_package=com.google.android.gms source_version=11509000 required_network_type=2 flex_time=600000 target_class=com.google.android.gms.checkin.EventLogService runtime=1506741123628 retry_strategy={"maximum_backoff_seconds":{"3600":0},"initial_backoff_seconds":{"30":0},"retry_policy":{"0":0}} last_runtime=0 period=1800000 task_type=1 job_id=-1 user_id=0
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: pending_ops.tag, pending_ops.target_class, pending_ops.target_package, pending_ops.user_id (code 2067)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at swi.a(:com.google.android.gms#11509280:208)
at sxo.a(:com.google.android.gms#11509280:64)
at sxp.handleMessage(:com.google.android.gms#11509280:29)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
09-30 03:02:15.888 1998-2721/com.google.android.gms.persistent E/NetworkScheduler: Error persisting task: com.google.android.gms/.checkin.EventLogService{u=0 tag="AggregationTaskTag" trigger=window{period=1800s,flex=600s,earliest=1787s,latest=2387s} requirements=[NET_ANY] attributes=[PERSISTED,RECURRING] scheduled=587s last_run=N/A jid=N/A status=PENDING retries=0}
09-30 03:03:37.417 1170-1578/? E/audio_hw_generic: Error opening input stream format 1, channel_mask 0010, sample_rate 16000
09-30 03:30:15.406 2159-21157/com.google.android.gms E/Herrevad: [355] RemoteReportsRefreshChimeraService.a: want to send authenticated request, but no Google account on device
09-30 03:30:15.511 2159-21162/com.google.android.gms E/ZappConnFactory: Unable to bind to PlayStore
09-30 03:30:15.518 2159-21168/com.google.android.gms E/ZappLogOperation: Unable to bind to Phonesky
09-30 03:30:15.526 2159-21162/com.google.android.gms E/ZappConnFactory: Unable to bind to PlayStore
09-30 03:30:15.526 2159-21162/com.google.android.gms E/ZappConnFactory: Unable to bind to PlayStore
09-30 03:30:15.551 2159-2678/com.google.android.gms E/Volley: [127] BasicNetwork.performRequest: Unexpected response code 307 for https://android.googleapis.com/nova/herrevad/network_quality_info
09-30 03:30:15.572 1170-1578/? E/Drm: Failed to find drm plugin
09-30 03:30:22.524 2159-2159/com.google.android.gms E/ActivityThread: Service com.google.android.gms.chimera.GmsIntentOperationService has leaked ServiceConnection ctn#2f714ea6 that was originally bound here
android.app.ServiceConnectionLeaked: Service com.google.android.gms.chimera.GmsIntentOperationService has leaked ServiceConnection ctn#2f714ea6 that was originally bound here
at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1077)
at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:971)
at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1774)
at android.app.ContextImpl.bindService(ContextImpl.java:1757)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at android.content.ContextWrapper.bindService(ContextWrapper.java:539)
at com.google.android.gms.chimera.container.zapp.ZappLogOperation.onHandleIntent(:com.google.android.gms#11509280:1)
at com.google.android.chimera.IntentOperation.onHandleIntent(:com.google.android.gms#11509280:2)
at bwy.run(:com.google.android.gms#11509280:10)
at bwv.run(:com.google.android.gms#11509280:14)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
09-30 03:44:15.607 1998-2721/com.google.android.gms.persistent E/SQLiteLog: (2067) abort at 31 in [INSERT INTO pending_ops(source,tag,requires_charging,target_package,source_version,required_network_type,flex_time,target_class,runtime,retry_strategy,last_runtime,period,task_type,job_id,user_
09-30 03:44:15.607 1998-2721/com.google.android.gms.persistent E/SQLiteDatabase: Error inserting source=4 tag=AggregationTaskTag requires_charging=0 target_package=com.google.android.gms source_version=11509000 required_network_type=2 flex_time=600000 target_class=com.google.android.gms.checkin.EventLogService runtime=1506743055606 retry_strategy={"maximum_backoff_seconds":{"3600":0},"initial_backoff_seconds":{"30":0},"retry_policy":{"0":0}} last_runtime=0 period=1800000 task_type=1 job_id=-1 user_id=0
android.database.sqlite.SQLiteConstraintException: UNIQUE constraint failed: pending_ops.tag, pending_ops.target_class, pending_ops.target_package, pending_ops.user_id (code 2067)
at android.database.sqlite.SQLiteConnection.nativeExecuteForLastInsertedRowId(Native Method)
at android.database.sqlite.SQLiteConnection.executeForLastInsertedRowId(SQLiteConnection.java:782)
at android.database.sqlite.SQLiteSession.executeForLastInsertedRowId(SQLiteSession.java:788)
at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:86)
at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1471)
at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1341)
at swi.a(:com.google.android.gms#11509280:208)
at sxo.a(:com.google.android.gms#11509280:64)
at sxp.handleMessage(:com.google.android.gms#11509280:29)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
09-30 03:44:15.607 1998-2721/com.google.android.gms.persistent E/NetworkScheduler: Error persisting task: com.google.android.gms/.checkin.EventLogService{u=0 tag="AggregationTaskTag" trigger=window{period=1800s,flex=600s,earliest=1199s,latest=1799s} requirements=[NET_ANY] attributes=[PERSISTED,RECURRING] scheduled=0s last_run=N/A jid=N/A status=PENDING retries=0}
09-30 03:44:15.637 2159-21184/com.google.android.gms E/Herrevad: [371] RemoteReportsRefreshChimeraService.a: want to send authenticated request, but no Google account on device
09-30 03:44:15.755 2159-2676/com.google.android.gms E/Volley: [126] BasicNetwork.performRequest: Unexpected response code 307 for https://android.googleapis.com/nova/herrevad/network_quality_info
09-30 03:46:13.425 1171-1171/? E/installd: eof
09-30 03:46:13.425 1171-1171/? E/installd: failed to read size
Here is the main activity code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager =(ViewPager) findViewById(R.id.pager);
PagerAdapter padapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(padapter);
//--------------------------------------------------------------------
init();
Action();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
}
else {
}
}
private void init(){
System.out.println("start---------------------");
textView_userIDVal = (TextView) findViewById(R.id.textView_userIDVal);
textView_parkingNoVal = (TextView) findViewById(R.id.textView_parkingNoVal);
textView_pillarNoVal = (TextView) findViewById(R.id.textView_pillarNoVal);
textView_colorVal = (TextView) findViewById(R.id.textView_colorVal);
imageView = (ImageView) findViewById(R.id.imageView);
button_space = (Button) findViewById(R.id.button_space);
button_scan = (Button) findViewById(R.id.button_scan);
button_find = (Button) findViewById(R.id.button_find);
simpleDateFormat = new SimpleDateFormat("MM/dd 'at' HH");
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
userID = Build.SERIAL;
//-------------error start next----------------
textView_userIDVal.setText("User ID : " + userID);
}
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, 200);
}
sharedPreferences = getSharedPreferences("Data", 0);
if(sharedPreferences.contains("parkingNum") && sharedPreferences.contains("time")) {
parkingNumtmp = sharedPreferences.getString("parkingNum", "");
textView_parkingNoVal.setText("Parking No. : " + parkingNumtmp + "\t(" + sharedPreferences.getString("time", "") + ")");
}
builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder_timeout = new AlertDialog.Builder(this);
builder_timeout.setTitle("REMIND");
builder_timeout.setMessage("Do you find your car ?");
builder_timeout.setCancelable(false);
builder_timeout.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
json_data = new JSONObject();
json_data.put("MT", "timeout");
json_data.put("PlaceMac", parkingNumtmp);
json_data.put("UserMac", userID);
json_write = new JSONObject();
json_write.put("Data", json_data);
json_write.put("Read", false);
isCloseScreen = false;
} catch (JSONException e) {
e.printStackTrace();
}
thread = new Thread(TCP);
thread.start();
timer_count = 0;
startFlag = false;
}
});
builder_timeout.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
maxTime = 10;
maxTime = maxTime / 2;
timer_count = 0;
startFlag = true;
}
});
}
private void Action(){
button_space.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
json_data = new JSONObject();
json_data.put("MT", "count");
json_write = new JSONObject();
json_write.put("Data", json_data);
json_write.put("Read", true);
//System.out.println(json_write + "\n");
} catch (JSONException e) {
e.printStackTrace();
}
thread = new Thread(TCP);
thread.start();
/*builder.setTitle("INFORMATION");
builder.setMessage("All : " + "\nNow : " );
AlertDialog alertDialog = builder.create();
alertDialog.show();*/
}
});
button_scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ScanActivity.class);
startActivityForResult(intent, REQUEST_CODE);
}
});
button_find.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(parkingNumtmp != null) {
try {
maxTime = 10;
json_data = new JSONObject();
json_data.put("MT", "search");
json_data.put("PlaceMac", parkingNumtmp);
json_data.put("UserMac", userID);
json_write = new JSONObject();
json_write.put("Data", json_data);
json_write.put("Read", true);
//System.out.println(json_write + "\n");
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Don't close the screen before you find your car ! ", Toast.LENGTH_LONG).show();
thread = new Thread(TCP);
thread.start();
}
else {
builder.setTitle("WARNING");
builder.setMessage("Please scan QRcode first!");
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
if(data != null) {
final Barcode barcode = data.getParcelableExtra("barcode");
parkingNumtmp = barcode.displayValue;
Date date = new Date();
final String time = simpleDateFormat.format(date);
sharedPreferences.edit().putString("parkingNum", parkingNumtmp).putString("time", time).commit();
textView_parkingNoVal.post(new Runnable() {
#Override
public void run() {
textView_parkingNoVal.setText("Parking No. : " + parkingNumtmp + "\t(" + time +")");
}
});
}
}
}
About Fragment. Is there any setting I have to do when I receive data form sever?
I want to put the received data to TextView in the another view .
Your init() function is probably try to find views inside fragments in view pager. However, at that moment, the fragments are not inflated yet, so your views in the activity are null and trying to do operation on them gives NPE. You should use onCreateView() of Fragment classes to find those views. Then you may notify main activity via callback mechanism.
For example, create FirstFragment as follows:
public class FirstFragment extends Fragment {
private OnFirstFragmentReadyListener callback;
#Override
public void onAttach(Context context) {
super.onAttach(context);
// This makes sure that the container activity has implemented the callback.
try {
callback = (OnFirstFragmentReadyListener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString()
+ " must implement OnFirstFragmentReadyListener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_first, container, false);
return rootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Notify the parent activity that the fragment is inflated.
callback.onFirstFragmentReady();
}
public interface OnFirstFragmentReadyListener {
void onFirstFragmentReady();
}
}
Let the layout of FirstFragment as follows (referenced above as fragment_first):
<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">
<TextView
android:id="#+id/first_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Assume we created two more similar fragment classes named as SecondFragment and ThirdFragment. Then the activity should be like this:
public class MainActivity extends AppCompatActivity implements FirstFragment.OnFirstFragmentReadyListener,
SecondFragment.OnSecondFragmentReadyListener, ThirdFragment.OnThirdFragmentReadyListener {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager =(ViewPager) findViewById(R.id.pager);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
// Don't call these functions here, spread them into callbacks.
// init();
// Action();
}
#Override
public void onFirstFragmentReady() {
TextView firstTextView = (TextView) findViewById(R.id.first_label);
...
// Now you have the views from FirstFragment instance.
// You can now call setText() or setOnClickListener() here.
}
#Override
public void onSecondFragmentReady() {
TextView secondTextView = (TextView) findViewById(R.id.second_label);
...
// Now you have the views from SecondFragment instance.
// You can now call setText() or setOnClickListener() here.
}
#Override
public void onThirdFragmentReady() {
TextView thirdTextView = (TextView) findViewById(R.id.third_label);
...
// Now you have the views from ThirdFragment instance.
// You can now call setText() or setOnClickListener() here.
}
}
Although this code works, this may not be the best way. I think it is better to do operations on views like setting texts or assigning OnClickListeners in fragments itself. If you need to notify a fragment after an action happened in the parent activity, you can implement public methods inside fragments and you can call them from the parent activity when needed.
In fragment you should call the function in onCreateView function(reason as mention by #Mehmed) which is something like below:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.your_fragment, container, false);
//all findViewById;
TextView yourTextView = (Text)view.findViewById(R.id.yourTextView);
//here call for your function
init();
// any other function goes here
return view;
}
I'm new to programming and have been assigned to code a simple music player, there were slides to help guide and I have slightly altered them (can't use the exact same variables).
So now it's error free but when I click on the play button it crashes, no idea why. Here's my code for the page where I select the library:
package sg.edu.tp.project1;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import sg.edu.tp.project1.util.AppUtil;
public class myMusic extends AppCompatActivity {
private String[] Musicsong = new String[6];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_music);
//store values in array of the first song
Musicsong[0] = "s1001";
Musicsong[1] = "The Way You Look Tonight";
Musicsong[2] = "ed sheeran";
Musicsong[3] = "a5b8972e764025020625bbf9c1c2bbb06e394a60?cid=null";
Musicsong[4] = "4.39";
Musicsong[5] = "music to play";
}
public void sendDataToActiviy(String[] song)
{
//1.create intent and specify destination
Intent intent = new Intent(this, PlayMusicActivity.class);
//2.store song info in intent to send to destination
intent.putExtra("id", song[0]);
intent.putExtra("title",song[1]);
intent.putExtra("artist",song[2]);
intent.putExtra("fileLink",song[3]);
intent.putExtra("coverArt",song[5]);
//3. launch desntination activiy
startActivity(intent);
}
public void handleSelection(View view)
{
// 1. get id of selected song
String resourceId = AppUtil.getResourceId(this, view);
//2. Search for the selected song based on the ID so that
// all infomation of the song can be retreived
String[] selectedSong =searchById(resourceId);
//3.popup to show tittle of song
AppUtil.popMessage(this, "Streaming song:" + selectedSong[1]);
//4. send song data to player screen
sendDataToActiviy(selectedSong);
}
private Object[] songs = {Musicsong};
public String[] searchById(String id) {
//temporary empty array
String[] song = null;
//for loop to get song
for (int index = 0; index < songs.length; index++) {
//3. store each song item to song array.
song = (String[]) songs[index];
//4. match song id to see if its the one i want
if (song[0].equals(id)) {
return song;
}
}
//if song not found in array empty array will be returned
return song;
}
}
This part where the player is:
package sg.edu.tp.project1;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.IOException;
import sg.edu.tp.project1.util.AppUtil;
public class PlayMusicActivity extends AppCompatActivity
{
//streaming website
private static final String BASE_URL = "https://p.scdn.co/mp3-preview/";
private String songId ="";
private String title = "";
private String artist = "";
private String fileLink = "";
private String coverArt = "";
private String url = "";
//builtin media player
private MediaPlayer player = null;
//position of song in playback
private int musicPosition = 0;
//button variable to link to play btn
private Button btnPlayPause = null;
private String[] Musicsong = {
"s1001",
"The Way You Look Tonight",
"ed sheeran",
"a5b8972e764025020625bbf9c1c2bbb06e394a60?cid=null",
"4.39",
"music to play"};
private Object[] songs = {Musicsong};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_music);
btnPlayPause = (Button) findViewById(R.id.btnPlayPause);
retrieveData();
displaySong(title,artist,coverArt);
}
private void retrieveData() {
Bundle songData = this.getIntent().getExtras();
songId = songData.getString("id");
title = songData.getString("title");
artist = songData.getString("artist");
fileLink = songData.getString("fileLink");
coverArt = songData.getString("coverArt");
url = BASE_URL + fileLink;
}
private void displaySong(String title, String artist, String coverArt)
{
//retrieve song title
TextView txtTitle = (TextView) findViewById(R.id.txtSongTitle);
//set text of song title
txtTitle.setText(title);
//retrieve artist
TextView txtArtist = (TextView) findViewById(R.id.txtArtist);
//set text of artist
txtArtist.setText(artist);
//get id of coverart
int imageId = AppUtil.getImageIdFromDrawable(this,coverArt);
//retrieve coverart
ImageView ivCoverArt = (ImageView) findViewById(R.id.imgCoverArt);
ivCoverArt.setImageResource(imageId);
}
public void playOrPauseMusic(View view)
{// start player
player.start();
//2.
btnPlayPause.setText("PAUSE");
//3.set the heading title of played song
setTitle("Now Playing:" + title + "-" + artist);
}
private void preparePlayer() { //create a new player
player = new MediaPlayer();
try {
//set stream type to music
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
//set source of music
player.setDataSource(url);
//prepare player for playback
player.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}}
Logs:
08-10 16:04:02.478 2567-2567/sg.edu.tp.project1 I/art: Not late-enabling -Xcheck:jni (already on)
08-10 16:04:02.478 2567-2567/sg.edu.tp.project1 W/art: Unexpected CPU variant for X86 using defaults: x86
08-10 16:04:02.535 2567-2567/sg.edu.tp.project1 W/System: ClassLoader referenced unknown path: /data/app/sg.edu.tp.project1-2/lib/x86
08-10 16:04:02.539 2567-2567/sg.edu.tp.project1 I/InstantRun: Starting Instant Run Server for sg.edu.tp.project1
08-10 16:04:02.913 2567-2567/sg.edu.tp.project1 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-10 16:04:03.399 2567-2632/sg.edu.tp.project1 I/OpenGLRenderer: Initialized EGL, version 1.4
08-10 16:04:03.400 2567-2632/sg.edu.tp.project1 D/OpenGLRenderer: Swap behavior 1
08-10 16:04:03.400 2567-2632/sg.edu.tp.project1 W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
08-10 16:04:03.400 2567-2632/sg.edu.tp.project1 D/OpenGLRenderer: Swap behavior 0
08-10 16:04:03.490 2567-2567/sg.edu.tp.project1 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
08-10 16:04:14.759 2567-2632/sg.edu.tp.project1 D/OpenGLRenderer: endAllActiveAnimators on 0x8d2e9b00 (RippleDrawable) with handle 0x8d2ff830
08-10 16:04:27.207 2567-2570/sg.edu.tp.project1 I/art: Do partial code cache collection, code=29KB, data=27KB
08-10 16:04:27.207 2567-2570/sg.edu.tp.project1 I/art: After code cache collection, code=29KB, data=27KB
08-10 16:04:27.207 2567-2570/sg.edu.tp.project1 I/art: Increasing code cache capacity to 128KB
08-10 16:04:27.463 2567-2632/sg.edu.tp.project1 D/OpenGLRenderer: endAllActiveAnimators on 0x8c313a00 (RippleDrawable) with handle 0x8d2ff420
08-10 16:04:29.695 2567-2567/sg.edu.tp.project1 D/AndroidRuntime: Shutting down VM
Beginning of crash:
08-10 16:04:29.696 2567-2567/sg.edu.tp.project1 E/AndroidRuntime: FATAL EXCEPTION: main
Process: sg.edu.tp.project1, PID: 2567
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at sg.edu.tp.project1.PlayMusicActivity.playOrPauseMusic(PlayMusicActivity.java:106)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
The exception message is very clear:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at sg.edu.tp.project1.PlayMusicActivity.playOrPauseMusic(PlayMusicActivity.java:106)
So your player field is null because you've never called PlayMusicActivity's preparePlayer() before.
I have been working on an app which needs to find some discoverable Bluetooth devices. I have followed guides and looked at answers on here and followed. However I cannot seem to get the phone to start scanning.
Here is the full activity code:
public class MainActivity extends AppCompatActivity {
private TextView scanningText;
private ListView scanningListView;
private Button scanningButton;
boolean scanComplete;
private final static int REQUEST_ENABLE_BT = 1;
private ArrayList<String> mDeviceList;
private BluetoothAdapter mBluetoothAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDeviceList = new ArrayList<>();
scanningButton = (Button) findViewById(R.id.scanningButton);
scanningText = (TextView) findViewById(R.id.scanningText);
scanningListView = (ListView) findViewById(R.id.scanningList);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
scanningText.setText("Your device does not support Bluetooth, Sorry!");
}
else if (!mBluetoothAdapter.isEnabled()) {
scanningText.setText("You need to enable bluetooth to use this app..");
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
// Register for broadcasts when a device is discovered.
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
scanningButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
scanningText.setText("Scanning...");
mBluetoothAdapter.startDiscovery();
}
});
}
#Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device.getName() + "\n" + device.getAddress());
Log.i("BT", device.getName() + "\n" + device.getAddress());
scanningListView.setAdapter(new ArrayAdapter<>(context,
android.R.layout.simple_list_item_1, mDeviceList));
}
else {
Log.i("BT", "none"+ "");
}
}
};
}
When I check the android log console, there are no logs.
Thanks
Update:
I have moved startDiscovery to the onclick listener.
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
// There are paired devices. Get the name and address of each paired device.
for (BluetoothDevice device : pairedDevices) {
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
}
Log.i("found", pairedDevices + "");
}
The following check takes place when i press the scan button. I am told the device is not discovering by the toast.
scanningButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
scanningText.setText("Scanning...");
mBluetoothAdapter.startDiscovery();
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.isDiscovering();
Toast toast = Toast.makeText(getApplicationContext(), "discovering", Toast.LENGTH_LONG);
toast.show();
}
else {
Toast toast = Toast.makeText(getApplicationContext(), "not discovering", Toast.LENGTH_LONG);
toast.show();
}
}
});
Entire Log:
06-14 14:50:13.356 25211-25211/? E/Zygote: v2
06-14 14:50:13.356 25211-25211/? I/libpersona: KNOX_SDCARD checking this for 10319
06-14 14:50:13.356 25211-25211/? I/libpersona: KNOX_SDCARD not a persona
06-14 14:50:13.357 25211-25211/? E/Zygote: accessInfo : 0
06-14 14:50:13.361 25211-25211/? W/SELinux: SELinux selinux_android_compute_policy_index : Policy Index[1], Con:u:r:zygote:s0 SPD:SEPF_SECMOBILE_7.0_0006 RAM:SEPF_SECMOBILE_7.0_0005, [-1 -1 0 1 0 1]
06-14 14:50:13.362 25211-25211/? I/SELinux: SELinux: seapp_context_lookup: seinfo=untrusted, level=s0:c512,c768, pkgname=com.smartscan.app.smartscanapp
06-14 14:50:13.365 25211-25211/? I/art: Late-enabling -Xcheck:jni
06-14 14:50:13.408 25211-25211/com.smartscan.app.smartscanapp W/System: ClassLoader referenced unknown path: /data/app/com.smartscan.app.smartscanapp-2/lib/arm64
06-14 14:50:13.417 25211-25211/com.smartscan.app.smartscanapp I/InstantRun: Instant Run Runtime started. Android package is com.smartscan.app.smartscanapp, real application class is null.
06-14 14:50:13.607 25211-25211/com.smartscan.app.smartscanapp W/System: ClassLoader referenced unknown path: /data/app/com.smartscan.app.smartscanapp-2/lib/arm64
06-14 14:50:13.688 25211-25211/com.smartscan.app.smartscanapp 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
06-14 14:50:13.770 25211-25211/com.smartscan.app.smartscanapp I/found: [C1:20:21:40:9C:65, 8C:C8:CD:BB:95:28, C9:50:76:7B:89:F2, 54:53:ED:A3:B1:70, 88:A3:F2:BE:DE:42, C4:73:1E:02:1F:6B, E4:04:39:29:74:E6]
06-14 14:50:13.826 25211-25250/com.smartscan.app.smartscanapp I/OpenGLRenderer: Initialized EGL, version 1.4
06-14 14:50:13.880 25211-25211/com.smartscan.app.smartscanapp I/InputMethodManager: [IMM] startInputInner - mService.startInputOrWindowGainedFocus
06-14 14:50:22.465 25211-25211/com.smartscan.app.smartscanapp W/System: ClassLoader referenced unknown path: /system/framework/QPerformance.jar
06-14 14:50:22.465 25211-25211/com.smartscan.app.smartscanapp E/BoostFramework: BoostFramework() : Exception_1 = java.lang.ClassNotFoundException: Didn't find class "com.qualcomm.qti.Performance" on path: DexPathList[[],nativeLibraryDirectories=[/system/lib64, /vendor/lib64]]
Try adding those permissions in the manifest :
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Also, it's always recommended to ask the user for permissions, so here you go :
if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
if(Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
}
You should start by adding logs at every steps.
Log.i("TAG", "Message")
Does your manifest file contains the appropriate permissions?
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
Next, it seems like you do not check if the bluetooth is enabled on the device. You should use an intent to do so.
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBT, REQUEST_BLUETOOTH);
}
I've been trying develop a custom camera application for my project. I have followed pretty much every steps on the android developers website for the deprecated android.hardware.Camera class, as I need to stay compatible for older devices. I have added the permission for the camera and the features for the camera and the autofocus. I am currently testing with the emulator provided by android studio, the Nexus 5 API 23 x86 with both front-facing and back-facing cameras set on emulated. When my code reaches the Camera.open() bit, I get the error -13: Fail to connect to camera service.
I moved my camera initialization at many places but it always throws that error and returns null. The built-in Camera app in the emulator does work properly for both camera and they are both detected in my code. I simply cannot find why it doesn't work.
Here's my code just in case:
CameraActivity.java
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*/
public class CameraActivity extends AppCompatActivity {
private static final boolean AUTO_HIDE = true;
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
private static final int UI_ANIMATION_DELAY = 300;
private View mControlsView;
private boolean mVisible;
private CameraView mCameraView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
mVisible = true;
mControlsView = findViewById(R.id.fullscreen_content_controls);
mCameraView = new CameraView(this);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_view);
preview.addView(mCameraView);
// Set up the user interaction to manually show or hide the system UI.
mCameraView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
toggle();
}
});
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
findViewById(R.id.capture_button).setOnTouchListener(mDelayHideTouchListener);
//// TODO: 2015-11-05 Create a preview class extending SurfaceView and implementing SurfaceHolder.callback and put camera code there
//// TODO: 2015-11-05 http://developer.android.com/guide/topics/media/camera.html#custom-camera
//// TODO: 2015-11-05 http://stackoverflow.com/questions/26305107/how-to-fix-fail-to-connect-to-camera-service-exception-in-android-emulator
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide(100);
}
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
private void toggle() {
if (mVisible) {
hide();
} else {
show();
}
}
private void hide() {
// Hide UI first
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.hide();
}
mControlsView.setVisibility(View.GONE);
mVisible = false;
// Schedule a runnable to remove the status and navigation bar after a delay
mHideHandler.removeCallbacks(mShowPart2Runnable);
mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
}
private final Runnable mHidePart2Runnable = new Runnable() {
#SuppressLint("InlinedApi")
#Override
public void run() {
// Delayed removal of status and navigation bar
// Note that some of these constants are new as of API 16 (Jelly Bean)
// and API 19 (KitKat). It is safe to use them, as they are inlined
// at compile-time and do nothing on earlier devices.
mCameraView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
};
#SuppressLint("InlinedApi")
private void show() {
// Show the system bar
mCameraView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
mVisible = true;
// Schedule a runnable to display UI elements after a delay
mHideHandler.removeCallbacks(mHidePart2Runnable);
mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY);
}
private final Runnable mShowPart2Runnable = new Runnable() {
#Override
public void run() {
// Delayed display of UI elements
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.show();
}
mControlsView.setVisibility(View.VISIBLE);
}
};
private final Handler mHideHandler = new Handler();
private final Runnable mHideRunnable = new Runnable() {
#Override
public void run() {
hide();
}
};
/**
* Schedules a call to hide() in [delay] milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide(int delayMillis) {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
#Override
protected void onPause(){
super.onPause();
mCameraView.releaseCamera();
}
}
CameraView.java
import android.hardware.Camera; //This is the good import!
/**
* TODO: document your custom view class.
*/
#SuppressWarnings("deprecation")
public class CameraView extends SurfaceView implements SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraView(Context context) {
super(context);
try{
mCamera = Camera.open();
} catch (Exception e){
Log.e("CameraView", "Error creating camera: " + e.getMessage());
}
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try{
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (IOException e){
Log.d("surfaceCreated", "Error starting camera preview: " + e.getMessage());
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
if(mHolder.getSurface() == null)
return;
try{
mCamera.stopPreview();
} catch (Exception e) {
//Non-existent o.O
}
//Resize, etc
try{
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (IOException e) {
Log.d("CameraView", "Error starting camera preview: " + e.getMessage());
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
if(mCamera != null)
mCamera.stopPreview();
}
public void releaseCamera(){
if(mCamera != null){
mCamera.release();
mCamera = null;
}
}
}
The logcat:
11-09 14:13:13.144 7791-7791/? I/art: Not late-enabling -Xcheck:jni (already on)
11-09 14:13:13.144 7791-7791/? I/art: Late-enabling JIT
11-09 14:13:13.146 7791-7791/? I/art: JIT created with code_cache_capacity=2MB compile_threshold=1000
11-09 14:13:13.212 7791-7791/com.weebly.olipro007.cameracontrol W/System: ClassLoader referenced unknown path: /data/app/com.weebly.olipro007.cameracontrol-1/lib/x86
11-09 14:13:13.427 7791-7791/com.weebly.olipro007.cameracontrol W/CameraBase: An error occurred while connecting to camera: 0
11-09 14:13:13.427 7791-7791/com.weebly.olipro007.cameracontrol E/CameraView: Error creating camera: Fail to connect to camera service
11-09 14:13:13.489 7791-7820/com.weebly.olipro007.cameracontrol D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
11-09 14:13:13.508 7791-7791/com.weebly.olipro007.cameracontrol D/: HostConnection::get() New Host Connection established 0xab645030, tid 7791
11-09 14:13:13.584 7791-7820/com.weebly.olipro007.cameracontrol D/: HostConnection::get() New Host Connection established 0xab6451c0, tid 7820
11-09 14:13:13.611 7791-7820/com.weebly.olipro007.cameracontrol I/OpenGLRenderer: Initialized EGL, version 1.4
11-09 14:13:13.693 7791-7820/com.weebly.olipro007.cameracontrol W/EGL_emulation: eglSurfaceAttrib not implemented
11-09 14:13:13.693 7791-7820/com.weebly.olipro007.cameracontrol W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xabdff9a0, error=EGL_SUCCESS
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol D/AndroidRuntime: Shutting down VM
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: FATAL EXCEPTION: main
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: Process: com.weebly.olipro007.cameracontrol, PID: 7791
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.hardware.Camera.setPreviewDisplay(android.view.SurfaceHolder)' on a null object reference
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at com.weebly.olipro007.cameracontrol.CameraView.surfaceCreated(CameraView.java:43)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.SurfaceView.updateWindow(SurfaceView.java:582)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:177)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:944)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2055)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.Choreographer.doCallbacks(Choreographer.java:670)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.Choreographer.doFrame(Choreographer.java:606)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:739)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:95)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.os.Looper.loop(Looper.java:148)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5417)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
11-09 14:13:13.699 7791-7791/com.weebly.olipro007.cameracontrol E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
11-09 14:13:16.909 7791-7791/? I/Process: Sending signal. PID: 7791 SIG: 9
Well it seems that the service was completely blocked for the old api in Marshmallow. I switched the emulator to lollipop and it loads...
myOnClickListener = new MyOnClickListener(this);
nRecyclerView = (RecyclerView) findViewById(R.id.my_recycler2_view);
nRecyclerView.setHasFixedSize(true);
static class MyOnClickListener implements View.OnClickListener{
private final Context context;
private MyOnClickListener(Context context) {
this.context = context;
}
public void onClick(View v) {
checkWhich(v);
}
private static void checkWhich (View v){
int selectedItemPosition = nRecyclerView.getChildPosition(v);
RecyclerView.ViewHolder nViewHolder = nRecyclerView.findViewHolderForPosition (selectedItemPosition);
TextView textViewName = (TextView) nViewHolder.itemView.findViewById(R.id.textViewCountry);
String selectedName = (String) textViewName.getText();
for (int i = 0; i < MyData.countryArray.length; i++){
if (selectedName==MyData.countryArray[i]) {
System.out.println(selectedName);
}
}
}
}
This has worked before, but isnt working now. Did I do anything wrong? I have 2 RecyclerViews but they are not visible together. This click listener is for one RecyclerView only.
LogCat
01-31 18:41:17.514 3441-3441/com.wc.gap.worldcupfixture I/art﹕ Late-enabling -Xcheck:jni
01-31 18:41:17.761 3441-3471/com.wc.gap.worldcupfixture D/OpenGLRenderer﹕ Render dirty regions requested: true
01-31 18:41:17.767 3441-3441/com.wc.gap.worldcupfixture D/Atlas﹕ Validating map...
01-31 18:41:17.792 3441-3471/com.wc.gap.worldcupfixture I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:410>: QUALCOMM Build: 10/24/14, 167c270, I68fa98814b
01-31 18:41:17.793 3441-3471/com.wc.gap.worldcupfixture I/OpenGLRenderer﹕ Initialized EGL, version 1.4
01-31 18:41:17.805 3441-3471/com.wc.gap.worldcupfixture D/OpenGLRenderer﹕ Enabling debug mode 0
01-31 18:41:57.529 3441-3470/com.wc.gap.worldcupfixture I/System.out﹕ 544, 543, 646, 797, 64, 66, 987
01-31 18:43:25.218 4242-4271/com.wc.gap.worldcupfixture D/OpenGLRenderer﹕ Render dirty regions requested: true
01-31 18:43:25.224 4242-4242/com.wc.gap.worldcupfixture D/Atlas﹕ Validating map...
01-31 18:43:25.257 4242-4271/com.wc.gap.worldcupfixture I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:410>: QUALCOMM Build: 10/24/14, 167c270, I68fa98814b
01-31 18:43:25.258 4242-4271/com.wc.gap.worldcupfixture I/OpenGLRenderer﹕ Initialized EGL, version 1.4
01-31 18:43:25.270 4242-4271/com.wc.gap.worldcupfixture D/OpenGLRenderer﹕ Enabling debug mode 0
When implementing View.OnClickListener, do it like below.
public class YourClass extends Activity implements View.OnClickListener
#Override
protected void onCreate(Bundle savedInstanceState) {
//Component setup here.
nRecyclerView = (RecyclerView) findViewById(R.id.my_recycler2_view);
nRecyclerView.setHasFixedSize(true);
nRecyclerView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
checkWhich(v);
}
private static void checkWhich (View v){
int selectedItemPosition = nRecyclerView.getChildPosition(v);
RecyclerView.ViewHolder nViewHolder = nRecyclerView.findViewHolderForPosition (selectedItemPosition);
TextView textViewName = (TextView) nViewHolder.itemView.findViewById(R.id.textViewCountry);
String selectedName = textViewName.getText().toString();
for (int i = 0; i < MyData.countryArray.length; i++){
if (selectedName==MyData.countryArray[i]) {
System.out.println(selectedName);
}
}
}
}