I have an App with a class that is responsible for requesting a JSON from a local server...
Here is the Main Activity:
public class Activity_main extends AppCompatActivity {
private ArrayList<StructAcount> netAcount = new ArrayList<StructAcount>();
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.txtJSON);
WebService.readUrl("http://localhost/match_picture/service.php?action=read");
String result = WebService.getResult();
if (result != null) {
try {
JSONArray tasks = new JSONArray(result);
for (int i=0; i<tasks.length(); i++) {
StructAcount acount= new StructAcount();
JSONObject object = tasks.getJSONObject(i);
acount.id = object.getLong("user_id");
acount.name = object.getString("user_name");
acount.email = object.getString("user_email");
netAcount.add(acount);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(Activity_main.this, "hsh" , Toast.LENGTH_SHORT).show();
}
for (StructAcount acount: netAcount) {
textView.setText(textView.getText() + "username: " + acount.name + " | " + "useremail: " + acount.email + "\n");
Toast.makeText(Activity_main.this, "username: " + acount.name + "\n" + "useremail: " + acount.email , Toast.LENGTH_SHORT).show();
}
}
}
...and here's the class for HTTP requests:
public class WebService {
private static String result;
public static void readUrl(String server_url) {
class GetJson extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
BufferedReader bufferedReader = null;
String uri = params[0];
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
InputStream in = new BufferedInputStream(con.getInputStream());
bufferedReader = new BufferedReader(new InputStreamReader(in));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json);
}
return sb.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
WebService.set_result(s);
}
}
GetJson gj = new GetJson();
gj.execute(server_url);
}
public static void set_result(String s) {
result = s;
}
public static String getResult() {
return result;
}
}
For the first time that I run the App, nothing was set to TextView.
When the App is still on emulator's screen: if I make a small change, for example, changing the text for a Toast message, I run the App again and TextView's text set by JSON values ...
Can anyone point some references or a solution for this situation?