JSONとPHPを使用してアプリケーションをMysqlデータベースに接続しようとしています。 PHPスクリプトは、ライトの状態(真または偽)を判断するJSON配列を返します。メインアクティビティへのJSONデータの受け渡し
URL接続を開き、ステータスを取得するJSONコードを別のクラスに配置しようとしました。その結果、私はそれを使用する必要があるときはいつでもそれを呼び出すことができます。
変数res
はJSONクラス内に値がありますが、JSONオブジェクトを使用してメインアクティビティからアクセスしようとすると空になります。この問題を解決するための正しい解決法を私に指示できますか?
主な活動
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クラス
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) {
}
}
}
非同期タスクの実行が完了する前に 't.setText(j.res);が起きています。すべてのUI操作は 'onPostExecute'を介して発生する必要があります – jitinsharma
@ muthana1990はい私の答えに示されているようにdoinback地面でnullを返すことはありませんはい、それを行う必要があります –
私は、意味があれば私のansを更新しました。 –