繁体   English   中英

无法在android TextView中打印JSON对象字符串

[英]Not able to print JSON object String in android TextView

所以我试图从看起来像这样的网站上获取JSON字符串

[{"name":"Painting"},{"name":"Painting or varnishing doors"},{"name":"Painting or varnishing frames"},{"name":"Varnishing floors"},{"name":"Picking old wallpaper"},{"name":"Painting the facade"},{"name":"professional athlete"}]

我只想获取带有字符串“ Painting”的第一个JSONObject。

这是我的MainActivity.java代码

package mobiletest.pixelapp.com.mobiletest;


import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import model.Cup;

public class MainActivity extends AppCompatActivity {
    private TextView textView;
    private String myString;
    private String anotherString;
    private String myVar;
    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textView = (TextView)findViewById(R.id.textView);
    Cup myCup = new Cup();
    String newString = myCup.myMethod();

    try {
        JSONArray jsonArray = new JSONArray(newString);
        JSONObject jsonObject = jsonArray.getJSONObject(0);
        Log.v("Key",jsonObject.getString("name"));
        textView.setText(jsonObject.getString("name"));
    } catch (JSONException e) {
        e.printStackTrace();
    }

    }
   }

这是我的Java类文件cup.java

package model;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by pruthvi on 12/2/2015.
 */
public class Cup {
    public String myMethod()
    {
        String output  = getUrlContents("http://xyz.co/tests/android-query.php");
        return output;
    }

    private static String getUrlContents(String theUrl)
    {
        StringBuilder content = new StringBuilder();

        // many of these calls can throw exceptions, so i've just
        // wrapped them all in one try/catch statement.
        try
        {
            // create a url object
            URL url = new URL(theUrl);

            // create a urlconnection object
            URLConnection urlConnection = url.openConnection();

            // wrap the urlconnection in a bufferedreader
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

            String line;

            // read from the urlconnection via the bufferedreader
            while ((line = bufferedReader.readLine()) != null)
            {
                content.append(line + "\n");
            }
            bufferedReader.close();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return content.toString();
    }
}

现在的问题是,当我以Java运行此代码时,我可以轻松地从JSONObject打印绘画,但是当我尝试通过为TextView设置文本来将其作为android视图运行时,我得到了一些奇怪的系统。

12-02 14:06:26.809 19250-19250/mobiletest.pixelapp.com.mobiletest D/libc: [NET] getaddrinfo  hn 10, servname NULL, ai_family 0+
12-02 14:06:26.809 19250-19250/mobiletest.pixelapp.com.mobiletest W/System.err:     at java.net.InetAddress.lookupHostByName(InetAddress.java:393)
12-02 14:06:26.809 19250-19250/mobiletest.pixelapp.com.mobiletest W/System.err:     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:244)
12-02 14:06:26.809 19250-19250/mobiletest.pixelapp.com.mobiletest W/System.err:     at java.net.InetAddress.getAllByName(InetAddress.java:219)

我是java和android的新手,到目前为止,我只想从远程服务器文件和数据库中获取数据。

提前致谢

在onCrate方法中这样做

try {
    JSONArray jsonArray = new JSONArray(newString);
for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject jsonObject = jsonArray.getJSONObject(i);
   String name = jsonObject.getString("name")
    textView.setText(name));}
} catch (JSONException e) {
    e.printStackTrace();
}

它将名称设置为textView。 乐于助人,乐于编码

看这个例子,它会给你一个想法

 AsyncTask<Void, Void, Void> asyncLoad = new AsyncTask<Void, Void, Void>()
        {
            @Override
            protected Void doInBackground(Void... params)
            {
                URL url = new URL("http://www.omdbapi.com/?i=&t="
                        + TITLE);
                String URL2="http://www.omdbapi.com/?i=&t=saw";
                Log.d("URL content", url.toString());
                HttpURLConnection urlConnection = (HttpURLConnection) url
                        .openConnection();
                Log.d("URL content", "register URL");
                urlConnection.connect();
                Log.d("URL connection", "establish connection");

                return null;
            }

            @Override
            protected void onPostExecute(Void result)
            {
                super.onPostExecute(result);
            }
        };

        asyncLoad.execute();

您无法在UI线程中执行网络任务。 所以

 String newString = myCup.myMethod();

无法正常工作。

这些错误的主要原因与线程上下文有关。

如果要使用android执行网络任务,请使用异步任务或其他网络库(我个人建议retrofit )。

 try 
    {
     JSONArray jsonArray = new JSONArray(newString);

     if(jarray.length()>0){

     String name = jarray.getJSONObject(0).getString("name");
     displayName(name);   //new method
    }catch(Exception e){
}

在onCreate()外部定义方法displayName(String

public void displayName(final  String name){

    runOnUiThread(new Runnable() {
         @Override
         public void run() {

        textView.setText(jsonObject.getString("name"));

         }
    });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM