java.net.UnknownHostException : api.openweathermap.org - java

I'm following a course on udacity 'Developing Android Apps'. Following is the code of ForecastFragment class which is suppose to get data in json format from the url(http://api.openweathermap.org/data/2.5/forecast/daily?q=Delhi,in&mode=json&cnt=7&units=metric).
public class ForecastFragment extends Fragment {
public ForecastFragment() {
}
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
String[] data = {
"Today-Sunny-34", "Tommorow-Rainy-233", "Wednesday-Cloudy-21", "Thursday-Monayblue-18", "Frida-Rainy-23", "Saturday-Rainy-22", "Sunday-Strorm-100"
};
List<String> weekForecast = new ArrayList<String>(Arrays.asList(data));
ArrayAdapter<String> mForecastAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item_forecast, R.id.list_item_forecast_textview, weekForecast);
ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
return rootView;
}
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater){
inflater.inflate(R.menu.forecastfragment, menu);
}
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if(id==R.id.action_refresh){
FetchWeatherTask fetch = new FetchWeatherTask();
fetch.execute();
return true;}
return super.onOptionsItemSelected(item);
}
public class FetchWeatherTask extends AsyncTask<Void,Void,Void>{
private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();
#Override
protected Void doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String forecastJsonStr = null;
try {
URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=Delhi,in&mode=json&cnt=7&units=metric");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) return null;
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) return null;
forecastJsonStr = buffer.toString();
Log.v(LOG_TAG,"Forecast Json String" + forecastJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error", e);
return null;
} finally {
if (urlConnection != null) urlConnection.disconnect();
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("placeholder fragment", "error closing stream", e);
}
}
}
return null;
}
}
}
However, I'm repeatedly getting this error.
07-20 12:49:14.063 2392-2486/com.example.android.sunshine.app E/FetchWeatherTask﹕ Error
java.net.UnknownHostException: api.openweathermap.org
at java.net.InetAddress.lookupHostByName(InetAddress.java:512)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:300)
at java.net.InetAddress.getAllByName(InetAddress.java:259)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:69)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:48)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect(HttpConnection.java:322)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:89)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpConnection(HttpURLConnectionImpl.java:285)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConnection(HttpURLConnectionImpl.java:267)
at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:205)
at com.example.android.sunshine.app.ForecastFragment$FetchWeatherTask.doInBackground(ForecastFragment.java:119)
at com.example.android.sunshine.app.ForecastFragment$FetchWeatherTask.doInBackground(ForecastFragment.java:83)
at android.os.AsyncTask$2.call(AsyncTask.java:185)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
at java.lang.Thread.run(Thread.java:1027)
Following are the things I've already checked:-
mobile phone has internet access.
AndroidManifest.xml declares the permission for internet usage.
The url works fine in the browser,but I'm clueless as to why this error is coming up.
Also, I'm running the app on my android phone(api 10).
If anyone could please provide a solution or point me in the right direction,it would be great. Thank you.

I had the same issue. Yet I did not turn WiFi on on my mobile phone. Activating wifi solved the problem for me.

I copied your Async class as-is and ran it in a new project on a KitKat VM on my Mac machine. Here are the results:
07-19 14:40:32.070 1670-1683/centerorbit.com.myapplication V/FetchWeatherTask﹕ Forecast Json String{"city":{"id":1273294,"name":"Delhi","coord":{"lon":77.216667,"lat":28.666668},"country":"IN","population":0},"cod":"200","message":0.0095,"cnt":7,"list":[{"dt":1437285600,"temp":{"day":29,"min":28.21,"max":29,"night":28.21,"eve":29,"morn":29},"pressure":984.15,"humidity":88,"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03n"}],"speed":1.66,"deg":64,"clouds":36},{"dt":1437372000,"temp":{"day":29.15,"min":25.17,"max":31.21,"night":27.92,"eve":31.21,"morn":26.55},"pressure":986.25,"humidity":95,"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],"speed":3.22,"deg":86,"clouds":88,"rain":10.65},{"dt":1437458400,"temp":{"day":30.46,"min":25.15,"max":31.57,"night":27.94,"eve":31.1,"morn":25.15},"pressure":988.81,"humidity":83,"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}],"speed":6.41,"deg":111,"clouds":68,"rain":0.45},{"dt":1437544800,"temp":{"day":30.63,"min":26.12,"max":32.69,"night":28.12,"eve":32.69,"morn":26.12},"pressure":991.01,"humidity":81,"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}],"speed":3.57,"deg":118,"clouds":64},{"dt":1437631200,"temp":{"day":34.27,"min":25.81,"max":35.34,"night":27.1,"eve":33.11,"morn":25.81},"pressure":989.86,"humidity":78,"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],"speed":2.06,"deg":74,"clouds":8,"rain":3.94},{"dt":1437717600,"temp":{"day":31.12,"min":25.71,"max":31.12,"night":26.68,"eve":30.83,"morn":25.71},"pressure":991.3,"humidity":0,"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],"speed":1.06,"deg":184,"clouds":13,"rain":7.82},{"dt":1437804000,"temp":{"day":31.68,"min":25.88,"max":32.17,"night":27.01,"eve":32.17,"morn":25.88},"pressure":989.57,"humidity":0,"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],"speed":1.28,"deg":226,"clouds":52,"rain":5.89}]}
It appears that your code is fine, and something is not right with your system/network. I would recommend restarting your phone/computer to see if that fixes the issue. If not, try using a different network (disconnect from your home WiFi and use Cell network).

You have registered permission in androidManifest to access Internet
<uses-permission android:name="android.permission.INTERNET"/>

Append APIKey at the end of URL
To get APIKey you have to create acount on openweathermap.org
e.g. http://api.openweathermap.org/data/2.5/forecast/daily?q=Delhi,in&mode=json&cnt=7&units=metric&appid=yourapiid"
Detail Process to Get APIKey is

Related

The application is minimized when the code is executed

I am writing the simplest application for Android. I receive all the HTML of the site and display this text on the smartphone screen. All this happens in Android Studio. Created a project using the "Fragment + ViewModel" template. In MainActiviti, using the getContent method, I connect to the site and read its HTML.
The method works, but as soon as I try to transfer the text to the screen, the application is immediately minimized on startup. Tell me what's wrong.
public class MainFragment extends Fragment{
final public String URL_POSTER = "https://udmfil.ru/";
public static MainFragment newInstance() {
return new MainFragment();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
DownLoad FOG = new DownLoad();
FOG.execute(URL_POSTER);
String result_post = String.valueOf(FOG);
Log.i("URL",result_post);
return inflater.inflate(R.layout.main_fragment, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
new ViewModelProvider(this).get(MainViewModel.class);
}
public class DownLoad extends AsyncTask<String,Void,String[]> {
#Override
protected String[] doInBackground(String... strings) {
HttpURLConnection connection = null;
BufferedReader reader= null;
try {
URL url = new URL(strings[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder buffer = new StringBuilder();
String line;
while ((line = reader.readLine()) != null)
buffer.append(line);
Log.i("URL", String.valueOf(buffer));
/*String pos = buffer.toString();
int indexPost, i = 1;
String postB;
do {
indexPost = pos.indexOf("m-img buy") + 21;
Log.i("URL", String.valueOf(indexPost));
if (indexPost != -1){
postB = pos.substring(indexPost, indexPost + 55);
Log.i("URL",postB);
strings[i] = postB;
indexPost = indexPost +55;
pos = pos.substring(indexPost);
Log.i("FLAG",pos);
i++;
Log.i("FLAG",strings[i]);
Log.i("URL", String.valueOf(i));
}
}while (indexPost != -1);*/
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
}catch (IOException e){
e.printStackTrace();
}
}
return strings;
}
}
}
error log:
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$4.done(Unknown Source:27)
at java.util.concurrent.FutureTask.finishCompletion(Unknown Source:36)
at java.util.concurrent.FutureTask.setException(Unknown Source:23)
at java.util.concurrent.FutureTask.run(Unknown Source:40)
at android.os.AsyncTask$SerialExecutor$1.run(Unknown Source:2)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source:79)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source:2)
at java.lang.Thread.run(Unknown Source:4)
Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
at java.net.Inet6AddressImpl.lookupHostByName(Unknown Source:111)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Unknown Source:22)
at java.net.InetAddress.getAllByName(Unknown Source:3)
at com.android.okhttp.Dns$1.lookup(Dns.java:41)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:178)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:144)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:86)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:176)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:128)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:97)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:289)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:232)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:465)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:131)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.connect(DelegatingHttpsURLConnection.java:90)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:30)
at com.example.myapplication.ui.main.MainFragment$DownLoad.doInBackground(MainFragment.java:58)
at com.example.myapplication.ui.main.MainFragment$DownLoad.doInBackground(MainFragment.java:48)
at android.os.AsyncTask$3.call(Unknown Source:20)
at java.util.concurrent.FutureTask.run(Unknown Source:31)
Caused by: android.system.GaiException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname)
at libcore.io.Linux.android_getaddrinfo(Native Method)
at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:74)
at libcore.io.BlockGuardOs.android_getaddrinfo(BlockGuardOs.java:200)
at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:74)
at java.net.Inet6AddressImpl.lookupHostByName(Unknown Source:51)
Caused by: android.system.ErrnoException: android_getaddrinfo failed: EACCES (Permission denied)
Now this is how it turns out.
As the message in the error log suggested, you have to add INTERNET permission to the Manifest file like below:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.stackoverflow">
<uses-permission android:name="android.permission.INTERNET" />
As you have not given the Internet permission host is not able to access the address and receive the data and in result it is getting crashed when you initiating the app.
Insert the below line in your menifest:
<uses-permission android:name="android.permission.INTERNET" />

How can I connect to web page, get status code to check if page available or not

I new to android programming and I had some problem that needs help, I'm stuck at this part for quite some time.
Problem: the code is successfully compiled, but making the connection to check make it crash. Can you help me by telling what is causing the issue and suggest me the solution or help improve my code. Thank you.
Process: the app check whether the app it wants to check is exist in google play store or not by checking its package name by sending simple HTTP connection. If the connection success to the app page in google play store, it will output a string that the page exists and it's a legit app.
Here is a snippet of my code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
output3 = findViewById(R.id.output3);
output3.setMovementMethod(ScrollingMovementMethod.getInstance());
connection();
}
public void connection(){
try {
String packagename = "com.facebook.katana";
URL url = new URL("http://play.google.com/store/apps/details?id="+packagename+"&hl=en");
URLConnection urlConn = url.openConnection();
HttpURLConnection con = (HttpURLConnection) urlConn;
con.setUseCaches(false);
con.setAllowUserInteraction(false);
con.setRequestMethod("GET");
con.connect();
int status = con.getResponseCode();
if (status == HttpURLConnection.HTTP_NOT_FOUND){
output3.append("not from google play store");
}
if (status == HttpURLConnection.HTTP_OK) {
output3.append("google App Store");
}
if (status != HttpsURLConnection.HTTP_NOT_FOUND && status != HttpsURLConnection.HTTP_OK)
output3.append("Other Response");
con.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
First of all HTTP requests are no longer support on the main thread so you must use a parallel Thread, or simple use an AsyncTask. Check below code for AsyncTask.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
output3 = findViewById(R.id.output3);
output3.setMovementMethod(ScrollingMovementMethod.getInstance());
AsyncTask.execute(new Runnable() {
#Override
public void run() {
connection();
}
});
}
Second thing is make sure Internet permission is added in your manifest.

Android - php mysql. no updated values

im new to android and php languages. I want to add point for students upon clicking a button in android. My database table is 'user' and my column that i want it to be updated is 'point'.
I tried to use this code for point.php that will be activate in onclick button in android.
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$point = $_POST['point_add'];
$myVar = $point;
var_dump($myVar);
$myVar= $myVar += 1;
var_dump($myVar);
//importing database connection script
require "init.php";
//Creating sql query
$sql = "UPDATE user SET point = '$point' WHERE id = $id;";
//Updating database table
if(mysqli_query($con,$sql)){
echo 'Data Updated Successfully';
}else{
echo 'Could Not Update Data Try Again';
}
//closing connection
mysqli_close($con);
}
?>
this is my init.php
<?php
error_reporting(0);
$db_name = "mymerit";
$mysql_user = "root";
$mysql_pass = "root";
$server_name = "localhost";
$con = mysqli_connect($server_name, $mysql_user, $mysql_pass, $db_name);
if(!$con){
echo '{"message":"Unable to connect to the database."}';
}
?>
and this is my point.java in android
public class Point extends Activity implements View.OnClickListener{
String Err;
TextView err;
Button badd;
Context ctx=this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.point);
badd = (Button) findViewById(R.id.point_add);
err = (TextView) findViewById(R.id.err);
Err = getIntent().getStringExtra("err");
badd.setOnClickListener(this);
err.setText(Err);
}
public void onClick(View v){
BackGround b = new BackGround();
Intent intent = new Intent(this, Thanks.class);
startActivity(intent);
}
class BackGround extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String point = params[0];
String data="";
int tmp;
try {
URL url = new URL("http://192.168.1.12/android/point.php");
String urlParams = "point="+point;
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
os.write(urlParams.getBytes());
os.flush();
os.close();
InputStream is = httpURLConnection.getInputStream();
while((tmp=is.read())!=-1){
data+= (char)tmp;
}
is.close();
httpURLConnection.disconnect();
return data;
} catch (MalformedURLException e) {
e.printStackTrace();
return "Exception: "+e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "Exception: "+e.getMessage();
}
}
#Override
protected void onPostExecute(String s) {
if(s.equals("")){
s="Data saved successfully.";
}
Toast.makeText(ctx, s, Toast.LENGTH_LONG).show();
}
}
}
There's no error and the android's working fine. but my point is not updated to 1. Is my code wrong somewhere?
Is the point.php the actual file? Because there is a lot wrong there. You defined the variable $sql 3 times, first two don't have any effect on the code. I assume it's a snipped because you used variables that haven't been defined in the files, could you please clean up point.php? If this is actually the entire file try removing that error_reporting(0) and work your way through the errors.
If i've understood properly, you want to add counter each click of button and push it into the database. So you could use sharedPref or simple do this, int counter =0,
OnClick of button counter += 1;
then you can push counter value in the database, Same you can try with string :)

File not found exception in Android for message toast

I am actually trying to search for given string in the text file which I have stored in the assets folder inside my Android application. The code that I have written is:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button;
final EditText obedittext;
button =(Button)findViewById(R.id.button1);
obedittext =(EditText)findViewById(R.id.editText1);
button.setOnClickListener(
new View.OnClickListener()
{
boolean textfound;
public void onClick(View view)
{
textfound = searchtext(obedittext.getText().toString());
if(textfound)
maketoast(obedittext.getText().toString());
else
maketoast("Unsuccessfull");
}
});
}
protected boolean searchtext(String string) {
// TODO Auto-generated method stub
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("mneumo.txt"));
while ((sCurrentLine = br.readLine()) != null) {
if(sCurrentLine.equals(string)) {
return true;
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
finally{
}
return false;
}
private void maketoast(String string) {
// TODO Auto-generated method stub
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, string , Toast.LENGTH_SHORT);
toast.show();
}
#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);
}
}
the error which I received was:
03-06 01:17:01.330: W/System.err(1170): java.io.FileNotFoundException: /mneumo.txt: open failed: ENOENT (No such file or directory)
03-06 01:17:01.330: W/System.err(1170): at libcore.io.IoBridge.open(IoBridge.java:409)
03-06 01:17:01.330: W/System.err(1170): at java.io.FileInputStream.<init>(FileInputStream.java:78)
03-06 01:17:01.340: W/System.err(1170): at java.io.FileInputStream.<init>(FileInputStream.java:105)
03-06 01:17:01.340: W/System.err(1170): at java.io.FileReader.<init>(FileReader.java:66)
03-06 01:17:01.340: W/System.err(1170): at com.example.demo.MainActivity.searchtext(MainActivity.java:60)
03-06 01:17:01.340: W/System.err(1170): at com.example.demo.MainActivity$1.onClick(MainActivity.java:41)
The sample file is,
SPINAL ANESTHESIA AGENTS
XYLOCAINE: WHERE NOT TO USE WITH EPINEPHRINE
GENERAL ANAESTHESIA: EQUIPMENT CHECK PRIOR TO INDUCING
If the string is found, it is supposed to show a toast with that string. But it always says "file not found". And I am total newbie.
This is for an app that is similar to a dictionary.
I did refer to other questions in this site but I still can't figure out what the problem is. Should I use assetmanager or something else?
Your code statement
br = new BufferedReader(new FileReader("mneumo.txt"));
refers to the wrong location. Hence, it can't read the file. Instead, replace your above line by following
br = new BufferedReader(new InputStreamReader(getAssets().open("mneumo.txt")));
This way, your file should be found and opened. Files stored in the app's asset folder should always read that way and not via hard-coded directory strings or app-relative paths.
You want to read from assets, right? You need to use AssetManager to pull that off. See below:
InputStream is;
try {
is = getAssets().open("myfile.txt");
byte[] buffer = new byte[is.available()];
is.read(buffer);
is.close();
Toast.makeText(this, new String(buffer, "UTF-8"), Toast.LENGTH_SHORT).show();
} catch (IOException ex) {
ex.printStackTrace();
}

android Java - Textview not appending text when activity restarts

I've been trying to create a function in my app that consist in a bluetooth RFID scanner, it's paired to my device and I have it working and all.
I can receive the text and log it in the console, when I compile the activity, everything goes fine, the stick reads the code, and then appends the text into an EditText, but if I go back and enter the activity again, I can see the code in the log, but the text doesn't go to the Edittext.
I tried a lot of different approaches, but nothing seems to work :/
here's the code I have:
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetooth);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> bondedSet = mBluetoothAdapter.getBondedDevices();
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available.", Toast.LENGTH_LONG).show();
}
if (!mBluetoothAdapter.isEnabled()) {
Toast.makeText(this, "Please enable your BT and re-run this program.", Toast.LENGTH_LONG).show();
finish();
}
if (mBluetoothAdapter.isEnabled()) {
if(bondedSet.size() == 1){
for(BluetoothDevice device : bondedSet){
address = device.getAddress();
Log.d("bt:", address);
}
}
}
String address = "00:A0:96:2A:0A:1B";
out = (EditText) findViewById(R.id.output);
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
Log.d(TAG, device.getName() + " connected");
myConnection = new ConnectThread(device);
myConnection.start();
}
private class ConnectThread extends Thread {
private final BluetoothSocket mySocket;
Message msg;
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null;
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.d(TAG, "CONNECTION IN THREAD DIDNT WORK");
}
mySocket = tmp;
}
Handler uiThreadHandler = new Handler() {
public void handleMessage(Message msg) {
out = (EditText) findViewById(R.id.output);
Object o = msg.obj;
out.append(o.toString().trim());
Log.d("handler", o.toString());
}
};
public void run() {
out = (EditText) findViewById(R.id.output);
Log.d(TAG, "STARTING TO CONNECT THE SOCKET");
setName("My Connection Thread");
InputStream inStream = null;
boolean run = false;
mBluetoothAdapter.cancelDiscovery();
try {
mySocket.connect();
run = true;
} catch (IOException e) {
Log.d(TAG, this.getName() + ": CONN DIDNT WORK, Try closing socket");
try {
mySocket.close();
Log.d(TAG, this.getName() + ": CLOSED SOCKET");
} catch (IOException e1) {
Log.d(TAG, this.getName() + ": COULD CLOSE SOCKET", e1);
this.destroy();
}
run = false;
}
synchronized (BluetoothActivity.this) {
myConnection = null;
}
byte[] buffer = new byte[1024];
int bytes;
// handle Connection
try {
inStream = mySocket.getInputStream();
while (run) {
try {
bytes = inStream.read(buffer);
readMessage = new String(buffer, 0, bytes);
msg = uiThreadHandler.obtainMessage();
msg.obj = readMessage;
uiThreadHandler.sendMessage(msg);
Log.d(TAG, "Received: " + readMessage);
} catch (IOException e3) {
Log.d(TAG, "disconnected");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
My guess is that this has something to do with the Thread itself. When you start your Activity for the first time, you also call .start() on the Thread, that would work fine.
The problem is when you leave your Activity and open it up again. In that case, one of onStop() or onPause() is called (depending on situation), and onRestart() or onResume() will be called afterwards respectively.
The trick comes now: Meanwhile all that process, your Thread is still running. As you show your code, it has not been stopped/paused, and keeps running all the time. So basically my tip is that there's something you do within your onCreate() method of your Activity that should also be done in your onPause() and onStop() events, and my another tip it's somewhere within your ConnectThread(BluetoothDevice device) method.
To know how to procceed, I'd firstly define both onStop() and onPause() methods within your Activity and see which is fired, log every attribute to see its value/state, and that way you'll be able to debug what is failing.
There's a diagram of the Activity lifecycle.
Problem was solved, the code works, and the TextView get the inputstream, the problem was when i left the activity, the thread continued to work, so far, no problem at all, after TONS of hours spent on this, i turn the TextView a static var and it worked :)
If anyone reads this, i hope it helps.

Categories