Url input stream not showing - java

I'm trying to get input stream from URL to be displayed on TextView when clicked on a certain button in my android app. I used someone else's code from internet tutorial step by step but it doesn't work for me. The TextView is always empty even though it should already show the text. I would deeply appreciate any help.
public class fetchData extends AsyncTask<Void, Void, Void> {
String data="";
#Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("https://api.myjson.com/bins/j5f6b");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
CurrencyConvert.text.setText(this.data);
}
}
public class CurrencyConvert extends AppCompatActivity {
Button click;
public static TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_currency_convert);
click = (Button) findViewById(R.id.button);
text = (TextView) findViewById(R.id.fetchText);
// data.setText("");
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fetchData process = new fetchData();
process.execute();
}
});
}
}

You shouldn't declare TextView as static varible of Activity class. Instead pass activity instance to fetchData class constructor (btw. class names should start with uppercase)
public class FetchData extends AsyncTask<Void, Void, Void> {
CurrencyConvert activity;
public FetchData(CurrencyConvert activity) {
this.activity= activity;
}
#Override
protected Void doInBackground(Void... arg0) {
// do background stuff...
}
#Override
protected void onPostExecute(Void result) {
activity.setTextInTextView(this.data);
}
In Your Activity declare public method for setting text:
public class CurrencyConvert extends AppCompatActivity {
Button click;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_currency_convert);
click = (Button) findViewById(R.id.button);
text = (TextView) findViewById(R.id.fetchText);
data.setText("");
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fetchData process = new fetchData(this);
process.execute();
}
});
}
void setTextInTextView(String data) {
text.setText(data);
}
}

Related

Cannot assign string from none one class to another

very noob in programming here, i have an activity (control) in android studio and a class (MesageSender) which extends AsyncTask ,
so i wanted to give a text in activity control via edittext and save that to a string in class messagesender and display it back to control in a textview , here is the code for my control (activity) and MessageSender (class)
below is code of control activity
public class controler extends AppCompatActivity {
public MessageSender mmessagesender = new MessageSender();
static EditText et;
Button bt;
static TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.activity_controler);
et= findViewById(R.id.editText);
bt = findViewById(R.id.button);
tv = findViewById(R.id.tv);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mmessagesender.ip = et.getText().toString();
}
});
}
}
Here ip is string from MessageSender class and et is edittext in controll activity
Below is code of MessageSender class
public class MessageSender extends AsyncTask<String,Void,Void> {
Socket s;
DataOutputStream dos;
PrintWriter pw;
String ip;
#Override
protected Void doInBackground(String... Voids) {
String message = Voids[0];
try{
s =new Socket(ip,123);
if(ip != null){
controler.tv.setText(ip);
}
else{
controler.tv.setText("no ip");
}
}
catch(IOException e) {
e.printStackTrace();
}
return null;
}
}
the problem was i cannot see the textview tv in control change to what i gave in edittext et
any help is appreciated , thanks :)

Large txt file reading via button waiting ages

Hi, why this code working "onCreate" but don`t working in the button
Realy I use not more then 20Mb, but for testing I inserted 90Mb
public class MainActivity extends AppCompatActivity {
TextView textView; DataInputStream textFileStream = null;
public void readbigtext(){
try {
textFileStream = new DataInputStream(getAssets().open(String.format("test1.txt")));
} catch (IOException e) {e.printStackTrace();}
Scanner sc = new Scanner(textFileStream);
while (sc.hasNextLine()) {textView.append(sc.nextLine());}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bigbutton = (Button) findViewById(R.id.bigbutton);
textView = (TextView) findViewById(R.id.bigfile);
textView.append("test begin");
//90Mb here IS WORKING!
// readbigtext();
bigbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//90Mb here DON`T WORKING
readbigtext();
}
});
}
}

Android: Show always a ProgressBar inside AsynckTask with runOnUIThread

There are an application that process many operations in an AsyncTask that has a runOnUIThread call.
The application has the code to show an indeterminate ProgressBar when the process it's doing in background, but the progress bar isn't shown always, in one cases yes, in other cases no.
With this model of (bad structure) code, how can I sure that the progress bar always is shown
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
public class AsyncTestActivity extends ActionBarActivity {
private ProgressDialog pd = null;
private void loadingBar(String titulo){
pd = ProgressDialog.show(this, titulo, "Please wait ...", true, false);
}
private void closeLoading(){
pd.dismiss();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_async_test);
TextView textView = (TextView) findViewById(R.id.textView);
Task async = new Task(textView);
async.execute("");
}
private class Task extends AsyncTask<String, Void, String> {
private TextView tv;
public Task(TextView tv) {
this.tv = tv;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingBar("Warning");//I want to show this always
}
#Override
protected String doInBackground(String... params) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
for(int i = 0; i <= 10; i++) {
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
return "End";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
tv.setText(result);
closeLoading();
}
}
}
I, can't change the structure (AsyncTask/runOnUIThread)the code because is big and I have few time to do this. The goal is that the progress bar always is ahowed. I had been reading that this is a bad practice, but the code was made by another person.
Did you ever try to call bringToFront() inside your onPreExecute():
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingBar.bringToFront();
loadingBar("Warning");//I want to show this always
}
(Untested code)
or if you want to make sure, you can include your progressBar as your Task parameter then directly execute bringToFront();
public Task(TextView tv, ProgressBar pB) {
this.tv = tv;
this.pb = pB.bringToFront();
}
hope it helps
Call loadingBar("Warning"); before async.execute("");.
If it's not showing, there is a problem with your ProgressDialog. Can you try edit loadingBar() method like this? :
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_async_test);
//init progress
pd = new ProgressDialog(this);
//
TextView textView = (TextView) findViewById(R.id.textView);
Task async = new Task(textView);
async.execute("");
}
private void loadingBar(String titulo){
pd.show();
pd.setTitle(titulo);
}

Combine Activity with Fragment

Learning what I can from the internet and youtube, I'm sure I am not handling this in the appropriate way. I have an existing app which includes a slide out navigation drawer using fragments. I am now trying to get an activity to run within that fragment without any luck. It works when ran on it's own, but after trying to combine the two, I am not able to get "draftactivity" to run properly. The fragment operates as it should.
public class tapsfragment extends Fragment {
public static tapsfragment newInstance() {
tapsfragment fragment = new tapsfragment();
return fragment;
}
public tapsfragment(){}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(2);
}
public class DraftActivity extends Activity {
TextView draftfeed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.draft_activity);
draftfeed = (TextView) findViewById(R.id.draftfeed);
new PostAsync().execute();
}
class PostAsync extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
XMLHelper helper;
#Override
protected void onPreExecute() {
pd = ProgressDialog.show(DraftActivity.this, "Taps", "Loading posts for ******.com ...", true, false);
}
#Override
protected Void doInBackground(Void... arg0) {
helper = new XMLHelper();
helper.get();
return null;
}
#Override
protected void onPostExecute(Void result) {
StringBuilder builder = new StringBuilder();
for (ItemValue post : helper.posts) {
builder.append("\nPost: " + post.getTitle());
builder.append("\n");
}
draftfeed.setText(builder.toString());
pd.dismiss();
}
}
Activity can't run in a fragment, it's the other way around.

Using another MainActivity? does it work?

Is it okay to do this? Creating another MainAcitivity since my original MainAcitivity is tied on the v4.view.pager activity_main. Although, this code doesn't post errors, this class seems to not be reflecting on the output. I'm using a tab pager adapter. Do I need to refresh or something? (It doesn't do anything that even the clickAction on this class doesn't work.
public class MainActivity2 extends Activity {
String url = "http://blog.compassion.com/living-in-the-philippines-rural-life/";
ProgressDialog mProgressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_fragment);
TextView titlebutton = (TextView) findViewById(R.id.TextView01);
titlebutton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// Execute Title AsyncTask
new Title().execute();
}
});
}
private class Title extends AsyncTask<Void, Void, Void> {
String body;
String title;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity2.this);
mProgressDialog.setTitle("Android Basic JSoup Tutorial");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
Document document = Jsoup.connect(url).get();
Elements elements = document.select("p");
title = document.title();
for(Element elements123 : elements){
body+=elements123.text();
System.out.println(elements123.text());
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
TextView txttbody = (TextView) findViewById(R.id.textView2);
txttbody.setMovementMethod(new ScrollingMovementMethod());
txttbody.setText(title +"\n"+body);
mProgressDialog.dismiss();
}
}
}

Categories

Resources