Android: Programmatically Turn on WiFi hotspot - java

I am trying to turn on the portable Wifi hotspot ON, by referring this link:
how to set advanced settings of android wifihotspot
This is working well on Samsung Galaxy S3 Android v4.4.2.(no issues)
But on other devices with the same or lower Android version, the application crashes and restarts the device.
The code is as follows:
package com.android.startwifi;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.app.Activity;
import android.content.Context;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class Main extends Activity {
public WifiManager wifiManager;
public Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("hi1","hi");
createWifiAccessPoint();
}
private void createWifiAccessPoint() {
WifiManager wifiManager = (WifiManager)getBaseContext().getSystemService(Context.WIFI_SERVICE);
if(wifiManager.isWifiEnabled())
{
wifiManager.setWifiEnabled(false);
}
Method[] wmMethods = wifiManager.getClass().getDeclaredMethods();
boolean methodFound=false;
for(Method method: wmMethods){
if(method.getName().equals("setWifiApEnabled")){
methodFound=true;
WifiConfiguration netConfig = new WifiConfiguration();
netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
try {
boolean apstatus=(Boolean) method.invoke(wifiManager, netConfig,true);
//statusView.setText("Creating a Wi-Fi Network \""+netConfig.SSID+"\"");
for (Method isWifiApEnabledmethod: wmMethods)
{
if(isWifiApEnabledmethod.getName().equals("isWifiApEnabled")){
while(!(Boolean)isWifiApEnabledmethod.invoke(wifiManager)){
};
for(Method method1: wmMethods){
if(method1.getName().equals("getWifiApState")){
int apstate;
apstate=(Integer)method1.invoke(wifiManager);
// netConfig=(WifiConfiguration)method1.invoke(wifi);
//statusView.append("\nSSID:"+netConfig.SSID+"\nPassword:"+netConfig.preSharedKey+"\n");
}
}
}
}
if(apstatus)
{
System.out.println("SUCCESSdddd");
//statusView.append("\nAccess Point Created!");
//finish();
//Intent searchSensorsIntent = new Intent(this,SearchSensors.class);
//startActivity(searchSensorsIntent);
}else
{
System.out.println("FAILED");
//statusView.append("\nAccess Point Creation failed!");
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
if(!methodFound){
//statusView.setText("Your phone's API does not contain setWifiApEnabled method to configure an access point");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Permissions that I have defined in the manifest file are:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
The log file generated is as follows:
09-10 18:35:01.644: D/jdwp(29752): prepping for JDWP over ADB
09-10 18:35:01.644: D/jdwp(29752): ADB transport startup
09-10 18:35:01.644: D/dalvikvm(29752): Elevating priority from 0 to -8
09-10 18:35:01.645: D/jdwp(29752): JDWP: thread running
09-10 18:35:01.645: D/jdwp(29752): acceptConnection
09-10 18:35:01.646: D/jdwp(29752): trying to receive file descriptor from ADB
09-10 18:35:01.646: D/dalvikvm(29752): zygote get thread init done
09-10 18:35:01.653: D/jdwp(29752): received file descriptor 34 from ADB
09-10 18:35:01.658: D/jdwp(29752): processIncoming
09-10 18:35:01.659: D/jdwp(29752): processIncoming
09-10 18:35:01.659: D/jdwp(29752): handlePacket : cmd=0x1, cmdSet=0xC7, len=0x13, id=0x40000040, flags=0x0, dataLen=0x8
09-10 18:35:01.661: D/jdwp(29752): processIncoming
09-10 18:35:01.661: D/jdwp(29752): handlePacket : cmd=0x1, cmdSet=0xC7, len=0x17, id=0x40000041, flags=0x0, dataLen=0xC
09-10 18:35:01.663: D/jdwp(29752): processIncoming
09-10 18:35:01.663: D/jdwp(29752): handlePacket : cmd=0x1, cmdSet=0xC7, len=0x13, id=0x40000042, flags=0x0, dataLen=0x8
09-10 18:35:01.665: D/jdwp(29752): processIncoming
09-10 18:35:01.665: D/jdwp(29752): handlePacket : cmd=0x1, cmdSet=0xC7, len=0x13, id=0x40000043, flags=0x0, dataLen=0x8
09-10 18:35:01.676: D/jdwp(29752): sendBufferedRequest : len=0x3D
09-10 18:35:01.736: D/jdwp(29752): sendBufferedRequest : len=0x45
09-10 18:35:01.754: W/asset(29752): AssetManager-->addDefaultAssets CIP path not exsit!
09-10 18:35:02.219: I/hi1(29752): hi
09-10 18:35:02.261: D/WifiManager(29752): Enter init, sThreadRefCount:0
09-10 18:35:02.268: D/WifiManager(29752): Create WifiManager handlerthread
09-10 18:35:03.599: I/System.out(29752): SUCCESSdddd
09-10 18:35:03.634: V/PhoneWindow(29752): DecorView setVisiblity: visibility = 4
09-10 18:35:03.745: V/PhoneWindow(29752): DecorView setVisiblity: visibility = 0
09-10 18:35:03.922: D/libEGL(29752): loaded /system/lib/egl/libEGL_mali.so
09-10 18:35:03.924: D/libEGL(29752): loaded /system/lib/egl/libGLESv1_CM_mali.so
09-10 18:35:03.927: D/libEGL(29752): loaded /system/lib/egl/libGLESv2_mali.so
09-10 18:35:04.111: D/OpenGLRenderer(29752): Enabling debug mode 0
09-10 18:35:10.610: E/InputEventReceiver(29752): channel '41f21f48 com.android.startwifi/com.android.startwifi.Main (client)' ~ Publisher closed input channel or an error occurred. events=0x9
Thus I have the following questions:
I would like to know why is this app behaving normally on Samsung S3
but not on other devices?
How can I fix this issue?

I had the same issue. You must to erase the following code line:
netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
That works for me in versions 4.1.1, 4.2 and 4.3.

Try this code .I test in android 5.0.1 :
public boolean setHotSpot(String SSID,String passWord){
Method[] mMethods = mWifiManager.getClass().getDeclaredMethods();
for(Method mMethod: mMethods){
if(mMethod.getName().equals("setWifiApEnabled")) {
WifiConfiguration netConfig = new WifiConfiguration();
if(passWord==""){
netConfig.SSID = SSID;
netConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
}else{
netConfig.SSID = SSID ;
netConfig.preSharedKey = passWord;
netConfig.hiddenSSID = true;
netConfig.status = WifiConfiguration.Status.ENABLED;
netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
netConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
netConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
netConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
}
try {
mMethod.invoke(mWifiManager, netConfig,false);
mWifiManager.saveConfiguration();
return true;
} catch (Exception e) {
e.getMessage();
}
}
}
return false;
}
Insert this permission in AndroidManifest:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />

If you are using WPA_PSK authentication, you have to specify preSharedKey.
netConfig.preSharedKey = "testPassword";
netConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
Otherwise it will crash and restart the device.

Related

ENOENT (No such file or directory) - when the file exists in Android Java

Trying Android development after some time, I am trying to download a zip file from FTP but even after repeat tries, still get FileNotFound Exception when i try to write the file in FileOutputStream. The file clearly exists on local storage as I am printing it 2-3 times (please check output log)
MainActivity.java
package com.example.myapplication;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.apache.commons.net.ftp.FTPFile;
import java.io.File;
public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = "";
Spinner drop;
Button btn;
String[] items;
FTPFile[] file;
ArrayAdapter adapter;
ProgressDialog mProgressDialog;
String dwnFile = "";
String localFilePath;
File localFile;
FTPOps ftp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button1);
drop = (Spinner) findViewById(R.id.spinner);
items = new String[]{"hello"};
String path = Environment.getExternalStorageDirectory().toString();
System.out.println("Path: " + path);
File directory = new File(path);
File[] files = directory.listFiles();
for (int i = 0; i < files.length; i++) {
System.out.println(files[i].getName());
}
items = new String[]{"Select the file", "01.zip", "04.zip", "05.zip", "06.zip", "07.zip", "08.zip", "09.zip",};
adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, items);
drop.setAdapter(adapter);
btn.setOnClickListener(v -> {
dwnFile = drop.getSelectedItem().toString().equals("Select the file") ? "" : drop.getSelectedItem().toString();
if (dwnFile != "") {
Context context = this;
localFilePath = Environment.getExternalStorageDirectory() + "/" + "ebooks";
localFile = new File(localFilePath + "/" + dwnFile);
System.out.println(localFile.mkdir() ? "File created" : "Not created file");
if (localFile.exists()) {
System.out.println("File created");
} else {
System.out.println("File edxists already");
}
System.out.println(localFile.getPath());
Toast toast = Toast.makeText(getApplicationContext(), "Downloading...", Toast.LENGTH_LONG);
toast.show();
ftp = new FTPOps(localFile, context, dwnFile);
String msg = (ftp.runDownloadAndUnziping()) ? "Downloaded" : "Error in downloding";
toast = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG);
toast.show();
}
});
}
}
The Mainactivity gives a drop down to select from list of files and sends the data to another class for FTP downlaod.
FTPOps.java
package com.example.myapplication;
import android.content.Context;
import android.widget.Toast;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FTPOps {
File localFile;
Context context;
FTPClient ftp;
String fileName;
public FTPOps(File localFile, Context context, String dwnFile) {
this.localFile = localFile;
this.context = context;
ftp = new FTPClient();
this.fileName = dwnFile;
}
public boolean runDownloadAndUnziping() {
setUpFTP();
return true;
}
private void setUpFTP() {
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
ftp.connect("some$$$$url");
ftp.login("someID", "somePassword");
showToast("Login into FTP Successful");
ftp.enterLocalPassiveMode();
ftp.setFileType(FTP.BINARY_FILE_TYPE);
System.out.println("Downlaod in progress for " + fileName);
System.out.println("Local file is " + localFile.getPath());
FileOutputStream fo = new FileOutputStream(localFile.getPath());
if (fo == null) {
System.out.println("fo is null");
}
boolean r = ftp.retrieveFile(fileName, fo);
if (r) {
System.out.println("Operation success");
}
fo.close();
} catch (IOException e) {
e.printStackTrace();
showToast("Login Failed");
}
}
private void showToast(String msg) {
System.out.println(msg);
}
});
t.start();
}
}
My Output log:
06/13 01:13:00: Launching 'app' on Nexus 6 API 30.
Install successfully finished in 1 s 683 ms.
$ adb shell am start -n "com.example.myapplication/com.example.myapplication.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 13263 on device 'emulator-5554'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
W/e.myapplicatio: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/e.myapplicatio: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
I/System.out: Path: /storage/emulated/0
I/System.out: Android
Music
Podcasts
Ringtones
Alarms
Notifications
Pictures
Movies
I/System.out: Download
DCIM
Audiobooks
Documents
D/HostConnection: HostConnection::get() New Host Connection established 0xf24e9f30, tid 13290
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_async_frame_commands ANDROID_EMU_gles_max_version_2
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/EGL_emulation: eglCreateContext: 0xf24ead30: maj 2 min 0 rcv 2
D/EGL_emulation: eglMakeCurrent: 0xf24ead30: ver 2 0 (tinfo 0xf28370f0) (first time)
I/Gralloc4: mapper 4.x is not supported
D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection established 0xf24ea390, tid 13290
D/goldfish-address-space: allocate: Ask for block of size 0x100
D/goldfish-address-space: allocate: ioctl allocate returned offset 0x3f9d95000 size 0x2000
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync ANDROID_EMU_vulkan_shader_float16_int8 ANDROID_EMU_vulkan_async_queue_submit GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_async_frame_commands ANDROID_EMU_gles_max_version_2
I/Choreographer: Skipped 40 frames! The application may be doing too much work on its main thread.
I/OpenGLRenderer: Davey! duration=760ms; Flags=0, IntendedVsync=24852661746550, Vsync=24853328413190, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=24853340948720, AnimationStart=24853340988320, PerformTraversalsStart=24853341581320, DrawStart=24853343717920, SyncQueued=24853344351620, SyncStart=24853344908520, IssueDrawCommandsStart=24853345141720, SwapBuffers=24853352646720, FrameCompleted=24853423084920, DequeueBufferDuration=981700, QueueBufferDuration=1455800, GpuCompleted=0,
W/e.myapplicatio: Accessing hidden field Landroid/widget/AbsListView;->mIsChildViewEnabled:Z (greylist, reflection, allowed)
D/OpenGLRenderer: endAllActiveAnimators on 0xec08c3d0 (DropDownListView) with handle 0xc3041870
I/System.out: Not created file
I/System.out: File edxists already
I/System.out: /storage/emulated/0/ebooks/06.zip
D/CompatibilityChangeReporter: Compat change id reported: 147798919; UID 10155; state: ENABLED
I/System.out: Login into FTP Successful
I/System.out: Downlaod in progress for 06.zip
***I/System.out: Local file is /storage/emulated/0/ebooks/06.zip***
**W/System.err: java.io.FileNotFoundException: /storage/emulated/0/ebooks/06.zip: open failed: ENOENT (No such file or directory)**
at libcore.io.IoBridge.open(IoBridge.java:492)
at java.io.FileOutputStream.<init>(FileOutputStream.java:236)
W/System.err: at java.io.FileOutputStream.<init>(FileOutputStream.java:125)
at com.example.myapplication.FTPOps$1.run(FTPOps.java:50)
at java.lang.Thread.run(Thread.java:923)
Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
at libcore.io.Linux.open(Native Method)
W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
at libcore.io.BlockGuardOs.open(BlockGuardOs.java:254)
W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:166)
at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:7542)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:478)
... 4 more
I/System.out: Login Failed
I remember earlier the download used to work like this, but I read some posts about storage access issues, so I updated my manifest appropriately with:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.MyApplication"
android:requestLegacyExternalStorage="true">
But result is same.
Now I need help in understanding:
Why do I get FileNotFoundException when file exists, as It can be seen printed on screen just before it crashes
Even the Toast which I remember used to work earlier is not working at all in MainActivity.java
Also I need to unzip the downloaded file, if anyone has a better suggestion for a new library or it still works the old way ?

Whenever Iam not entering anything in EditText the app is crashes [duplicate]

This question already has answers here:
Can't create handler inside thread that has not called Looper.prepare()
(30 answers)
Closed 2 years ago.
Iam making a weather app but whenever Iam not entering or entering wrong city name in EditText the app crashes even though I have used try and catch blocks for error handling.The below is the java,xml code and the logs where it is showing a runtime error.
Java
package com.atul.whatstheweather;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
EditText cityName;
TextView weatherInfo;
public class Content extends AsyncTask<String, Void ,String>
{
#Override
protected String doInBackground(String... urls) {
URL url;
HttpURLConnection urlConnection = null;
String result = "";
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while(data != -1)
{
char current = (char)data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
Toast.makeText(MainActivity.this, "URL malfunctioned", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
String weatherData = jsonObject.getString("weather");
JSONArray array = new JSONArray(weatherData);
for(int i=0;i<array.length();i++)
{
JSONObject jsonPart = array.getJSONObject(i);
String main = jsonPart.getString("main");
String description = jsonPart.getString("description");
weatherInfo.setText("Weather: "+main+"\n\n"+"Description: "+description);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cityName = (EditText)findViewById(R.id.cityName);
weatherInfo = (TextView)findViewById(R.id.textView);
}
public void clicked(View view)
{
Content content = new Content();
content.execute("https://api.openweathermap.org/data/2.5/weather?q=" + cityName.getText().toString() + "&appid=c20cea76c84b519d67d4e6582064db92");
Log.i("clicked","is working");
}
}
In the Logs given below it is showing Runtime error
Run Logs
05/03 17:35:25: Launching app
Cold swapped changes.
$ adb shell am start -n "com.atul.whatstheweather/com.atul.whatstheweather.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 18757 on device xiaomi-redmi_note_3-9b51ac51
I/art: Late-enabling -Xcheck:jni
D/TidaProvider: TidaProvider()
W/ReflectionUtils: java.lang.NoSuchMethodException: android.os.MessageQueue#enableMonitor()#bestmatch
at miui.util.ReflectionUtils.findMethodBestMatch(ReflectionUtils.java:338)
at miui.util.ReflectionUtils.findMethodBestMatch(ReflectionUtils.java:375)
at miui.util.ReflectionUtils.callMethod(ReflectionUtils.java:800)
at miui.util.ReflectionUtils.tryCallMethod(ReflectionUtils.java:818)
at android.os.BaseLooper.enableMonitor(BaseLooper.java:47)
at android.os.Looper.prepareMainLooper(Looper.java:111)
at android.app.ActivityThread.main(ActivityThread.java:5586)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:774)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:652)
W/ResourceType: No package identifier when getting name for resource number 0x00000000
W/System: ClassLoader referenced unknown path: /data/app/com.atul.whatstheweather-1/lib/arm64
I/InstantRun: Instant Run Runtime started. Android package is com.atul.whatstheweather, real application class is null.
W/System: ClassLoader referenced unknown path: /data/app/com.atul.whatstheweather-1/lib/arm64
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
D/AccessibilityManager: current package=com.atul.whatstheweather, accessibility manager mIsFinalEnabled=false, mOptimizeEnabled=false, mIsUiAutomationEnabled=false, mIsInterestedPackage=false
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#9df51ef
V/BoostFramework: BoostFramework() : mPerf = com.qualcomm.qti.Performance#ce6e4fc
D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
I/Adreno: QUALCOMM build : a7823f5, I59a6815413
Build Date : 09/23/16
OpenGL ES Shader Compiler Version: XE031.07.00.00
Local Branch : mybranch22028469
Remote Branch : quic/LA.BR.1.3.3_rb2.26
Remote Branch : NONE
Reconstruct Branch : NOTHING
I/OpenGLRenderer: Initialized EGL, version 1.4
E/HAL: hw_get_module_by_class: module name gralloc
E/HAL: hw_get_module_by_class: module name gralloc
I/clicked: is working
I/DpmTcmClient: RegisterTcmMonitor from: com.android.okhttp.TcmIdleTimerMonitor
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.atul.whatstheweather, PID: 18757
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:356)
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:266)
at com.atul.whatstheweather.MainActivity$Content.doInBackground(MainActivity.java:60)
at com.atul.whatstheweather.MainActivity$Content.doInBackground(MainActivity.java:31)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
at java.lang.Thread.run(Thread.java:818) 
I/Process: Sending signal. PID: 18757 SIG: 9
Application terminated.
App crashes because you are calling Toast in background thread.
Replace your Toast line in catch block Toast.makeText(MainActivity.this, "URL malfunctioned", Toast.LENGTH_SHORT).show(); with :
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "URL malfunctioned", Toast.LENGTH_SHORT).show();
}
});
Just delete the Toast.makeText

Android my class in not onCreate() method. but exception System services not available to Activities before onCreate()

recently I work A.class in coding.
I know why show this exception.
but my class not onCreate() method
A class extends BaseContent
basecontent is abstract class.
basecontent not onCreate() method.
how can I processor ?
java.lang.IllegalStateException: System services not available to Activities before onCreate()
Here's the code:
private OnClickListener mConnectOnClick = new OnClickListener() {
#Override
public void onClick(View v) {
final WifiConfiguration config = Wifi.getWifiConfiguration(mWifiManager, mScanResult, mScanResultSecurity);
boolean connResult = false;
if (config != null) {
connResult = Wifi.connectToConfiguredNetwork(mFloating, mWifiManager, config, false); //WI-FI connect
final Dialog dialog = new Dialog(v.getContext());
dialog.setCanceledOnTouchOutside(false);
dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
dialog.getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
| View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
dialog.setContentView(R.layout.dialog);
dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE);
ConnectivityManager cm = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
int m_iNetworkType = (activeNetwork == null) ? -1 : activeNetwork.getType();
dialog.dismiss();
}
else {
dialog.show();
}
}
if (!connResult) {
Toast.makeText(mFloating, R.string.toastFailed, Toast.LENGTH_LONG).show();
}
}
};
Here's the exception:
: FATAL EXCEPTION: main
Process: kr.co.iosystem.wificonnecter, PID: 4521
java.lang.IllegalStateException: System services not available to Activities before onCreate()
at android.app.Activity.getSystemService(Activity.java:4532)
at kr.co.iosystem.wificonnecter.connecter.ConfiguredNetworkContent$1.onClick(ConfiguredNetworkContent.java:263)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)

Android Fatal signal 11 (SIGSEGV), code 1, fault addr 0x0 in tid 29092

I'm try to play a loading animation on my loading screen, and I read somewhere that android doesn't support gifs so either you have to break in into frames and then play it or we can use the Movie class.
Heres the leading activity -
package com.myapp.mehul.login.activity;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import com.myapp.mehul.login.MYGIFView;
import com.myapp.mehul.login.MainActivity;
import com.myapp.mehul.login.R;
import com.myapp.mehul.login.app.Constants;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URISyntaxException;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
/**
* Created by mehul on 2/6/16.
*/
public class LoadingScreen extends Activity {
/** Duration of wait **/
private final int SPLASH_DISPLAY_LENGTH = 1000;
/** Called when the activity is first created. */
private Socket mSocket;
String you;
String opponentId;
String username;
{
try {
mSocket = IO.socket(Constants.CHAT_SERVER_URL);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(new MYGIFView(getApplicationContext()));
//initialise the socket
mSocket.connect();
//call add user
mSocket.emit("add user");
//start a listener for opponent
mSocket.on("opponent", onOpponent);
//initialise the username
username = getIntent().getExtras().getString("username");
}
private Emitter.Listener onOpponent = new Emitter.Listener(){
#Override
public void call(final Object... args){
LoadingScreen.this.runOnUiThread(new Runnable() {
#Override
public void run() {
JSONObject data = (JSONObject) args[0];
try {
you = data.getString("you");
opponentId = data.getString("opponent");
Log.d("LoadingScreen", data.toString());
//setResult(RESULT_OK, i);
finish();
} catch (JSONException e) {
return;
}
Intent i = new Intent(LoadingScreen.this, MainActivity.class);
i.putExtra("opponentId", opponentId);
i.putExtra("you", you);
i.putExtra("username", username);
Log.d("goToChat", username);
startActivity(i);
}
});
}
};
#Override
public void onBackPressed(){
AlertDialog.Builder builder = new AlertDialog.Builder(LoadingScreen.this);
builder.setMessage("I knew you didn't have BALLS.").setCancelable(
false).setPositiveButton("I am a LOSER",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//send the logout information to the server
JSONObject discon = new JSONObject();
try {
discon.put("opponent", opponentId);
discon.put("you", you);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mSocket.emit("discon", discon);
mSocket.disconnect();
//finish the current activity.
Intent intent = new Intent(LoadingScreen.this, MainMenu.class);
startActivity(intent);
LoadingScreen.this.finish();
}
}).setNegativeButton("I'll fkin face it",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
In the above code I've set content view by passing it an instance of MYGIFView.class -
Heres MYGIFView.class
package com.myapp.mehul.login;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Movie;
import android.view.View;
import java.io.InputStream;
/**
* Created by mehul on 2/7/16.
*/
public class MYGIFView extends View{
Movie movie,movie1;
InputStream is=null,is1=null;
long moviestart;
public MYGIFView(Context context) {
super(context);
is=context.getResources().openRawResource(+ R.drawable.loading);
movie=Movie.decodeStream(is);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
super.onDraw(canvas);
long now=android.os.SystemClock.uptimeMillis();
System.out.println("now="+now);
if (moviestart == 0) { // first time
moviestart = now;
}
System.out.println("\tmoviestart="+moviestart);
int relTime = (int)((now - moviestart) % movie.duration()) ;
System.out.println("time="+relTime+"\treltime="+movie.duration());
movie.setTime(relTime);
movie.draw(canvas,this.getWidth()/2-20,this.getHeight()/2-40);
this.invalidate();
}
}
The loading activity IS creating an instance of MYGIFView.class and it logs the data but then it gives fatal signal 11. I tried to search but I didn't get any answer.
console log -
02-07 12:22:30.321 29092-29092/? I/art: Late-enabling -Xcheck:jni
02-07 12:22:30.341 29092-29102/? I/art: Debugger is no longer active
02-07 12:22:30.422 29092-29092/? D/SQLiteHandler: Fetching user from Sqlite: {username=Harsh}
02-07 12:22:30.422 29092-29092/? D/LoginActivity: already logged in
02-07 12:22:30.425 29092-29092/? I/Timeline: Timeline: Activity_launch_request id:com.myapp.mehul.login time:71360781
02-07 12:22:30.487 29092-29092/? D/MainMenu: painted again
02-07 12:22:30.490 29092-29092/? D/SQLiteHandler: Fetching user from Sqlite: {username=Harsh}
02-07 12:22:30.554 29092-29149/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
02-07 12:22:30.559 29092-29092/? D/Atlas: Validating map...
02-07 12:22:30.596 29092-29149/? I/Adreno-EGL: <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.01.00.042.030_msm8974_LA.BF.1.1.1_RB1__release_AU ()
OpenGL ES Shader Compiler Version: E031.25.03.06
Build Date: 04/15/15 Wed
Local Branch: mybranch9068252
Remote Branch: quic/LA.BF.1.1.1_rb1.19
Local Patches: NONE
Reconstruct Branch: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.01.00.042.030 + NOTHING
02-07 12:22:30.597 29092-29149/? I/OpenGLRenderer: Initialized EGL, version 1.4
02-07 12:22:30.611 29092-29149/? D/OpenGLRenderer: Enabling debug mode 0
02-07 12:22:30.660 29092-29092/? I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#387f1572 time:71361016
02-07 12:22:31.898 29092-29092/com.myapp.mehul.login D/go to chat: was called
02-07 12:22:31.899 29092-29092/com.myapp.mehul.login I/Timeline: Timeline: Activity_launch_request id:com.myapp.mehul.login time:71362255
02-07 12:22:31.997 29092-29092/com.myapp.mehul.login I/System.out: now=71362353
02-07 12:22:31.997 29092-29092/com.myapp.mehul.login I/System.out: moviestart=71362353
02-07 12:22:31.997 29092-29092/com.myapp.mehul.login I/System.out: time=0 reltime=1850
02-07 12:22:32.007 29092-29092/com.myapp.mehul.login A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0x0 in tid 29092 (app.mehul.login)
02-07 12:22:32.541 29092-29092/com.myapp.mehul.login W/app.mehul.login: type=1701 audit(0.0:302): auid=4294967295 uid=10250 gid=10250 ses=4294967295 subj=u:r:untrusted_app:s0 reason="memory violation" sig=11
I received a batch for this question which means its being viewed a lot, so I'll answer this question -
What I figured out was the line below was throwing the error -
movie.draw(canvas,this.getWidth()/2-20,this.getHeight()/2-40);
Now the problem is that this error specifically can be caused by lots of reasons, its never a specific reason.. the reason mine wasn't working out was because my device didn't work well with hardware acceleration, so I just had to disable it in the manifest application, like this -
<android:hardwareAccelerated="false">
Now its possible that the reason might not be the same....but the core reason is the same, its memory related, and most chances are its a bug in the firmware of the device or emulator you are testing upon.
In the Manifest set in your activity :
<activity
android:name="LoadingScreen"
android:hardwareAccelerated="false">
</activity>
I got here with the exact same problem but in React Native, so I will put a solution for those who need it too. The error may be triggered by react-native-webview and/or React Navigation. In some cases, like me, you don't want to disable Hardware Acceleration on the whole app, so here's a workaround:
react-native-webview
<WebView
androidHardwareAccelerationDisabled
source={source}
/>
React Navigation 5
<NavigationContainer>
<Stack.Navigator initialRouteName="HomeScreen">
<Stack.Screen
name="HomeScreen"
component={HomeScreen}
options={{
animationEnabled: false,
}}
/>
</Stack.Navigator>
</NavigationContainer>
https://github.com/react-native-webview/react-native-webview/issues/575

File read presents none of files actual data

Hi I am trying to print a text file with the double data, line by line, read from a file on my android device however it doesn't seem to be working what is wrong? I get no errors but not proper print out?
in my bodyTempInfo View I get readout:
Your Body Temperature Readings are:[]
my temp2.txt file, there is a total of 1440 numbers, not going to paste them all here
37.06750839
36.89390613
36.88484785
36.81941363
36.81815453
36.97372599
37.0510889
36.90421803
36.90452867
36.81245808
36.91739551
37.05989195
36.80757783
36.85141347
37.04927826
36.80384926
36.94000689
37.04948705
37.07007973
36.95211596
37.05161886
36.97029703
37.03218835
36.89381629
My bodyTempInfo.Java
package com.teamfara.circadianrhythmmonitor4;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class bodyTempInfo extends AppCompatActivity {
ArrayList<Double> currentBodyTemp;
public void displayCurrentBodyTempArray(View view) throws FileNotFoundException {
ArrayList<Double> list = new ArrayList<>();
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
//Read text from file
File file = new File(sdcard, "temp2.txt");
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
list.add(Double.parseDouble(line));
text.append('\n');
}
br.close();
}
catch(IOException e) {
}
/*
Scanner file2 = new Scanner(new File(sdcard, "temp.txt"));
while (file2.hasNextLine()) {
String line = file2.nextLine();
Scanner scanner = new Scanner(line);
scanner.useDelimiter(",");
while (scanner.hasNextDouble()) {
list.add(scanner.nextDouble());
}
scanner.close();
}
*/
currentBodyTemp = list;
displayBodyTemp("Your Body Temperature Readings are:" + list);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_body_temp_info);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
try {
displayCurrentBodyTempArray(findViewById(R.id.bodyTempInfoArray));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
private void displayBodyTemp(String bodyTemp) {
TextView textView = (TextView) findViewById(R.id.bodyTempInfoArray);
textView.setText(bodyTemp);
}
}
logcat
10-25 14:15:11.041 11084-11084/? E/Zygote: MountEmulatedStorage()
10-25 14:15:11.041 11084-11084/? E/Zygote: v2
10-25 14:15:11.041 11084-11084/? I/libpersona: KNOX_SDCARD checking this for 10385
10-25 14:15:11.041 11084-11084/? I/libpersona: KNOX_SDCARD not a persona
10-25 14:15:11.051 11084-11084/? I/SELinux: Function: selinux_compare_spd_ram , priority [2] , priority version is VE=SEPF_SM-G920V_5.1.1_0033
10-25 14:15:11.051 11084-11084/? E/SELinux: [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
10-25 14:15:11.051 11084-11084/? I/art: Late-enabling -Xcheck:jni
10-25 14:15:11.111 11084-11084/? D/TimaKeyStoreProvider: TimaSignature is unavailable
10-25 14:15:11.111 11084-11084/? D/ActivityThread: Added TimaKeyStore provider
10-25 14:15:11.211 11084-11084/com.teamfara.circadianrhythmmonitor4 I/InjectionManager: Inside getClassLibPath + mLibMap{0=, 1=}
10-25 14:15:11.231 11084-11084/com.teamfara.circadianrhythmmonitor4 I/InjectionManager: Inside getClassLibPath caller
10-25 14:15:11.241 11084-11084/com.teamfara.circadianrhythmmonitor4 D/InjectionManager: InjectionManager
10-25 14:15:11.241 11084-11084/com.teamfara.circadianrhythmmonitor4 D/InjectionManager: fillFeatureStoreMap com.teamfara.circadianrhythmmonitor4
10-25 14:15:11.241 11084-11084/com.teamfara.circadianrhythmmonitor4 I/InjectionManager: Constructor com.teamfara.circadianrhythmmonitor4, Feature store :{}
10-25 14:15:11.241 11084-11084/com.teamfara.circadianrhythmmonitor4 I/InjectionManager: featureStore :{}
10-25 14:15:11.301 11084-11084/com.teamfara.circadianrhythmmonitor4 D/SecWifiDisplayUtil: Metadata value : SecSettings2
10-25 14:15:11.491 11084-11084/com.teamfara.circadianrhythmmonitor4 D/PhoneWindow: *FMB* installDecor mIsFloating : false
10-25 14:15:11.491 11084-11084/com.teamfara.circadianrhythmmonitor4 D/PhoneWindow: *FMB* installDecor flags : -2139029248
10-25 14:15:11.761 11084-11084/com.teamfara.circadianrhythmmonitor4 D/Activity: performCreate Call Injection manager
10-25 14:15:11.771 11084-11084/com.teamfara.circadianrhythmmonitor4 I/InjectionManager: dispatchOnViewCreated > Target : com.teamfara.circadianrhythmmonitor4.MainActivity isFragment :false
10-25 14:15:11.791 11084-11175/com.teamfara.circadianrhythmmonitor4 D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
10-25 14:15:11.821 11084-11084/com.teamfara.circadianrhythmmonitor4 D/PhoneWindow: *FMB* isFloatingMenuEnabled mFloatingMenuBtn : null
10-25 14:15:11.821 11084-11084/com.teamfara.circadianrhythmmonitor4 D/PhoneWindow: *FMB* isFloatingMenuEnabled return false
10-25 14:15:11.891 11084-11084/com.teamfara.circadianrhythmmonitor4 D/SRIB_DCS: log_dcs ThreadedRenderer::initialize entered!
10-25 14:15:11.951 11084-11175/com.teamfara.circadianrhythmmonitor4 D/libEGL: loaded /vendor/lib64/egl/libGLES_mali.so
10-25 14:15:11.991 11084-11175/com.teamfara.circadianrhythmmonitor4 I/OpenGLRenderer: Initialized EGL, version 1.4
10-25 14:15:12.001 11084-11175/com.teamfara.circadianrhythmmonitor4 I/OpenGLRenderer: HWUI protection enabled for context , &this =0x7f79c8abc0 ,&mEglDisplay = 1 , &mEglConfig = 1912140464
10-25 14:15:12.011 11084-11175/com.teamfara.circadianrhythmmonitor4 D/OpenGLRenderer: Get maximum texture size. GL_MAX_TEXTURE_SIZE is 8192
10-25 14:15:12.011 11084-11175/com.teamfara.circadianrhythmmonitor4 D/OpenGLRenderer: Enabling debug mode 0
10-25 14:15:12.011 11084-11175/com.teamfara.circadianrhythmmonitor4 D/mali_winsys: new_window_surface returns 0x3000, [1440x2560]-format:1
10-25 14:15:12.391 11084-11084/com.teamfara.circadianrhythmmonitor4 I/InjectionManager: dispatchCreateOptionsMenu :com.teamfara.circadianrhythmmonitor4.MainActivity
10-25 14:15:12.391 11084-11084/com.teamfara.circadianrhythmmonitor4 I/InjectionManager: dispatchPrepareOptionsMenu :com.teamfara.circadianrhythmmonitor4.MainActivity
10-25 14:15:12.461 11084-11084/com.teamfara.circadianrhythmmonitor4 I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#2f8d81aa time:4028871
10-25 14:15:12.801 11084-11084/com.teamfara.circadianrhythmmonitor4 V/ActivityThread: updateVisibility : ActivityRecord{81a0e76 token=android.os.BinderProxy#2f8d81aa {com.teamfara.circadianrhythmmonitor4/com.teamfara.circadianrhythmmonitor4.MainActivity}} show : true
10-25 14:15:14.701 11084-11084/com.teamfara.circadianrhythmmonitor4 I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#2f8d81aa time:4031112
10-25 14:15:14.921 11084-11084/com.teamfara.circadianrhythmmonitor4 D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN
10-25 14:15:14.971 11084-11084/com.teamfara.circadianrhythmmonitor4 I/Timeline: Timeline: Activity_launch_request id:com.teamfara.circadianrhythmmonitor4 time:4031384
10-25 14:15:15.051 11084-11084/com.teamfara.circadianrhythmmonitor4 D/PhoneWindow: *FMB* installDecor mIsFloating : false
10-25 14:15:15.051 11084-11084/com.teamfara.circadianrhythmmonitor4 D/PhoneWindow: *FMB* installDecor flags : -2139029248
10-25 14:15:15.071 11084-11084/com.teamfara.circadianrhythmmonitor4 D/Activity: performCreate Call Injection manager
10-25 14:15:15.121 11084-11084/com.teamfara.circadianrhythmmonitor4 I/InjectionManager: dispatchOnViewCreated > Target : com.teamfara.circadianrhythmmonitor4.bodyTempInfo isFragment :false
10-25 14:15:15.121 11084-11084/com.teamfara.circadianrhythmmonitor4 D/SecWifiDisplayUtil: Metadata value : SecSettings2
10-25 14:15:15.141 11084-11084/com.teamfara.circadianrhythmmonitor4 D/PhoneWindow: *FMB* isFloatingMenuEnabled mFloatingMenuBtn : null
10-25 14:15:15.141 11084-11084/com.teamfara.circadianrhythmmonitor4 D/PhoneWindow: *FMB* isFloatingMenuEnabled return false
10-25 14:15:15.181 11084-11084/com.teamfara.circadianrhythmmonitor4 D/SRIB_DCS: log_dcs ThreadedRenderer::initialize entered!
10-25 14:15:15.181 11084-11175/com.teamfara.circadianrhythmmonitor4 D/mali_winsys: new_window_surface returns 0x3000, [1440x2560]-format:1
10-25 14:15:15.201 11084-11084/com.teamfara.circadianrhythmmonitor4 I/InjectionManager: dispatchCreateOptionsMenu :com.teamfara.circadianrhythmmonitor4.bodyTempInfo
10-25 14:15:15.201 11084-11084/com.teamfara.circadianrhythmmonitor4 I/InjectionManager: dispatchPrepareOptionsMenu :com.teamfara.circadianrhythmmonitor4.bodyTempInfo
10-25 14:15:15.271 11084-11084/com.teamfara.circadianrhythmmonitor4 I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#1f826b14 time:4031688
10-25 14:15:15.311 11084-11084/com.teamfara.circadianrhythmmonitor4 V/ActivityThread: updateVisibility : ActivityRecord{81a0e76 token=android.os.BinderProxy#2f8d81aa {com.teamfara.circadianrhythmmonitor4/com.teamfara.circadianrhythmmonitor4.MainActivity}} show : false
My content_body_temp_info.xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_body_temp_info"
tools:context="com.teamfara.circadianrhythmmonitor4.bodyTempInfo">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text = "Body Temperature Measurements will go here"
android:id = "#+id/bodyTempInfoArray"/>
</RelativeLayout>
my MainActivity.java
package com.teamfara.circadianrhythmmonitor4;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private final static int REQUEST_ENABLE_BT = 1;
UUID myUUID = UUID.randomUUID();
private static final int DISCOVER_DURATION = 300;
private static final int REQUEST_BLU = 1;
ArrayAdapter<String> mArrayAdapter;
ArrayList<Double> currentBodyTemp;
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBIntent, REQUEST_ENABLE_BT);
}
//If there are paired devices
/*Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
//Loop through the paired devices
for (BluetoothDevice device : pairedDevices) {
//add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
*/
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
ArrayList<Double> lightInfo;
public void sendLightFile() {
String filename = "lightInfo";
String string = "Here is light info" + lightInfo;
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(string.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
// Send information over bluetooth?
}
public void goToBodyInfo(View view) {
Intent intent = new Intent(this, bodyTempInfo.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void sendLight(View view) {
Intent intent = new Intent(this, ConnectTest.class);
startActivity(intent);
}
// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket,
// because mmServerSocket is final
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("CircadianRhythmMonitor", myUUID);
} catch (IOException e) {
}
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
//manageConnectedSocket(socket);
//mmServerSocket.close();
break;
}
}
}
/**
* Will cancel the listening socket, and cause the thread to finish
*/
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) {
}
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
// mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
//.sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private void displayBodyTemp(String bodyTemp) {
TextView textView = (TextView) findViewById(R.id.bodyTempInfoArray);
textView.setText(bodyTemp);
}
}
my AndroidManfiest.xml
package="com.teamfara.circadianrhythmmonitor4" >
<!-- Allows bluetooth to be used from this app -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.NFC" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".bodyTempInfo"
android:label="#string/title_activity_body_temp_info"
android:parentActivityName=".MainActivity"
android:theme="#style/AppTheme.NoActionBar" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.teamfara.circadianrhythmmonitor4.MainActivity" />
</activity>
<activity
android:name=".ConnectTest"
android:label="#string/title_activity_body_temp_info"
android:parentActivityName=".MainActivity"
android:theme="#style/AppTheme.NoActionBar" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.teamfara.circadianrhythmmonitor4.MainActivity" />
</activity>
</application>
<uses-feature
android:name="android.hardware.nfc"
android:required="true" />
</manifest>
In your displayBodyTemp() function, you are passing a String and using + to add an arraylist. That is the story.You need to pass a string only. Or override the toString() method of the Arraylist
OR, try this:
displayBodyTemp("Your Body Temperature Readings are:" + text);

Categories

Resources