簡體   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