Reputation: 77
URL = http://troyka.esy.es/numberofrows.php
if you put that in your browser you'l get a number (currently it's 9)
I'm trying to pull that number to my android app and display it on a textview
I've tried this method but it shows me nothing on the emulator internet and network permission are set on manifest
textview id = "textView"
What am I doing wrong?
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class MainActivity extends Activity {
public static String ans;
private TextView T1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
T1 = new TextView(this);
T1 = (TextView) findViewById(R.id.textView);
T1.setText(ans);
}
public String getDATA() throws IOException {
String fullString = "";
URL url = new URL("http://troyka.esy.es/numberofrows.php");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
fullString += line;
}
reader.close();
return fullString;
}
public void setAns() throws IOException {
ans = getDATA();
}
}
Upvotes: 1
Views: 1063
Reputation: 5626
Try this answer please:
First, create an AsyncTask class like this to do the actual HTTP request for you outside the android main thread:
public class FetchColumnAsync extends AsyncTask<String, Void, String>
{
private Context mContext;
public FetchColumnAsync( Context ctx){
this.mContext = ctx;
}
protected String doInBackground(String... urls)
{
String fullString = "";
try{
URL url = new URL(urls[0]);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
fullString += line;
}
reader.close();
}catch(Exception e ){
e.getMessage();
}
return fullString;
}
@Override
protected void onPostExecute(String value){
try{
((OnValueFetchedListener) mContext).onValueFetched(value);
}catch(ClassCastException e){}
}
public interface OnValueFetchedListener{
void onValueFetched(String columns);
}
}
Then in your activity class, implement the above interface like this;
public class MainActivity extends Activity implements FetchColumnAsync.OnValueFetchedListener{
public static String ans;
private TextView T1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
T1 = (TextView) findViewById(R.id.textView);
//missing piece of code here
new FetchColumnAsync(this).execute("http://troyka.esy.es/numberofrows.php");
}
@Override
public void onValueFetched(String value){
T1.setText(value);
}
}
Upvotes: 1