无法在android TextView中打印JSON对象String

时间:2015-12-02 08:37:40

标签: java android json

所以我试图从一个看起来像这个

的网站上获取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视图运行时,我得到一些奇怪的系统.err

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的新手,截至目前我只想从远程服务器文件和数据库中获取数据。

提前致谢

4 个答案:

答案 0 :(得分:0)

在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。 乐于助人和快乐的编码

答案 1 :(得分:0)

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

 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();

答案 2 :(得分:0)

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

 String newString = myCup.myMethod();

没有正常工作。

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

如果你想用android做网络任务,请使用异步任务或其他网络库(我个人推荐retrofit)。

答案 3 :(得分:0)

 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"));

         }
    });
}