【问题标题】:I would like to effect the TextView from the json data I get from httpurlconnection我想从我从 httpurlconnection 获得的 json 数据中影响 TextView
【发布时间】:2017-12-18 05:23:01
【问题描述】:
//[(START)File:ThirdActivity.java] -->
package com.example.caleb.splash_screen;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.IOException;
import java.io.OutputStream;


public class ThirdActivity extends AppCompatActivity {
  //public String  text = "https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoItem.txt";


    public TextView text;

    private void writeStream(OutputStream out){
        String output = "Hello world";

       // out.write(output.getBytes());
        //out.flush();
    }


    /*private String readStream(InputStream is) {
        try {`enter code here`
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            int i = is.read();
            while(i != -1) {
                bo.write(i);
                i = is.read();
            }
            return bo.toString();
        } catch (IOException e) {
            return "";
        }
    }*/

    //[(START) readStream -->
    private String readStream(InputStream in) throws IOException {
    BufferedReader bin = new BufferedReader(new InputStreamReader(in));
    //temporary
        try {
            StringBuilder sb = new StringBuilder();
            String inputLine;
            while ((inputLine = bin.readLine()) != null) {
                sb.append(inputLine);
            }
            return sb.toString();


        } finally {

        }
    }
    //[(END) readStream -->


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_third2);

        text = (TextView)findViewById(R.id.textView);

        new JSONTask().execute("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoItem.txt");

    }

}
//[(END)File:ThirdActivity] -->







//[(START)File:JSONTask] -->

package com.example.caleb.splash_screen;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v4.widget.TextViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by Caleb on 12/17/2017.
 */

public class JSONTask extends AsyncTask<String,String,String> {


//final TextView txt = (TextView)findViewById(R.id.textView);
    private Context context;

    public JSONTask(Activity ThirdActivity) {
        context = ThirdActivity;
    }

@Override
    protected String doInBackground(String... params) {
        BufferedReader reader = null;
        HttpURLConnection urlConnection = null;
        //{(START)] Working Connection:ALERT! Error within code will cause crash -->
        try {
            URL url = new URL(params[0]);
            Log.w("testing", "test");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(false);
            urlConnection.connect();
            //urlConnection.setChunkedStreamingMode(0);
            //OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
            //writeStream(out);
            /*int a = urlConnection.getResponseCode();
            String b = String.valueOf(a);
            Log.e(b, "yesssssssssssssssss");*/

            InputStream in = urlConnection.getInputStream();
            //InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            reader = new BufferedReader(new InputStreamReader(in));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            /*String data = readStream(in);
            /*final TextView textView = (TextView) findViewById(R.id.textView);
            textView.setText("hello");
            */

            return buffer.toString();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            throw new RuntimeException(e);

        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //{(END)] Working Connection -->
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        TextView text = (TextView) ((AppCompatActivity) context).findViewById(R.id.textView);
        text.setText(result);

    }

}
//[(END)File:JSONTask] -->

/想要的效果/

块引用

我想从 url 指向的 json 文件中提取数据,并在名为 textView 的 UI 中更改 TextView。我不明白如何访问 AsyncTask 中的 findviewbyid。我在整个互联网上都找遍了,找不到任何东西:(任何建议都非常感谢!!

【问题讨论】:

    标签: java google-app-engine


    【解决方案1】:

    尝试弱引用以获取异步任务中的文本视图

    //调用异步任务

    new JSONTask(yourTextView).execute();
    

    //在你的异步任务中

      private final WeakReference<TextView> textViewReference;
    
        public JSONTask (TextView textView){
             textViewReference = new WeakReference<TextView>( textView);
        }
    
    
        @Override
        protected void onPostExecute() {
    
    
                TextView textView = textViewReference.get();
                //set values to text view
    
        }
    

    【讨论】:

      【解决方案2】:

      我正在使用 OkHttp 在我的应用程序中执行相同的任务

      • HTTP/2 支持允许对同一主机的所有请求共享一个套接字。

      • 连接池可减少请求延迟(如果 HTTP/2 不可用)。

      • 透明 GZIP 可缩小下载大小。

      • 响应缓存完全避免网络重复请求。

      添加这个依赖

      implementation 'com.squareup.okhttp3:okhttp:3.9.1'
      

      然后创建/编码一个名为OkHttpHandler的新类

      class OkHttpHandler extends AsyncTask<String, String, String> {
      
              OkHttpClient client = new OkHttpClient();
              private volatile String data;
      
              public String getResult() {
                  return data;
              }
      
              @Override
              protected String doInBackground(String... params) {
      
                  try {
                      Request.Builder builder = new Request.Builder();
                      builder.url(params[0]);
                      Request request = builder.build();
      
                      Response response = client.newCall(request).execute();
                      return response.body().string();
                  } catch (Exception e) {
                      e.printStackTrace();
                  }
                  return null;
              }
      
              @Override
              protected void onPostExecute(String s) {
                  super.onPostExecute(s);
                  data = s;
              }
          }
      }
      

      并像这样使用它

      String str = new OkHttpHandler().execute("http://www.<TEST>.com/json").get();
      

      我还建议检查 Wi-fi-Connected/Bluetooth-ConnectedPhoneData-Enabled 是否为 false if true/else,继续执行您的代码

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-28
        • 1970-01-01
        • 1970-01-01
        • 2020-08-31
        • 2018-01-13
        • 1970-01-01
        • 1970-01-01
        • 2023-01-25
        相关资源
        最近更新 更多