I am trying to connect my app to Mysql database using JSON and PHP. The PHP script returns a JSON array which determine the status of the light (true or false).
I tried to put the JSON code, which open the URL connection and get the status,in separate class. As a result, I can call it whenever I need to use it.
The problem is that the variable res
does have a value inside the JSON class but when I tried to access it from the main Activity using JSON object, it is empty. Can any one direct me to the right solution to solve this problem?
Main activity
public class MainActivity extends AppCompatActivity {
public TextView t;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t = (TextView) findViewById(R.id.t1);
Json j = new Json();
j.execute("http://127.0.0.1/web/test.php");
t.setText(j.res);
}
}
Json class
public class Json extends AsyncTask<String, String, String> {
String result = "";
public String res="";
@Override
protected void onPreExecute() {
}
@Override
protected String doInBackground(String... params) {
InputStream isr = null;
try {
String URL = params[0];
java.net.URL url = new URL(URL);
URLConnection urlConnection = url.openConnection();
isr = new BufferedInputStream(urlConnection.getInputStream());
} catch (Exception e) {
Log.e("log_tag", "error in http conection" + e.toString());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(isr, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result = sb.toString();
} catch (Exception e) {
Log.e("Log", "failed " + e.toString());
}
return null;
}
JSONObject json;
protected void onPostExecute(String result2) {
try {
String password1 = "";
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
json = jArray.getJSONObject(i);
res=json.getString("status");
break;
}
} catch (Exception e) {
}
}
}