简体   繁体   中英

Not able to print JSON object String in android TextView

So I am trying to fetch JSON string from a website which looks like this

[{"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"}]

I just want to fetch the first JSONObject with the string "Painting".

Here's my MainActivity.java code

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

    }
   }

Here's my java class file 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();
    }
}

Now the problem, when I run this code as java I am easily able to print painting from the JSONObject, but when I try to run it as an android view by setting the text for my TextView, I am getting some strange system.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)

I am new to java and android, and as of now I just want to get data from my remote server files and database.

Thanks in advance

Do like that in onCrate Method

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

It will set name to textView. Happy to Help and Happy Coding

look at this example it will give you an idea

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

You can't do network task in UI Thread. So

 String newString = myCup.myMethod();

not properly working.

Main Reason of those errors are related with thread context.

If you want to do network task with android, use async task or other network library (personally I recommend 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){
}

Define the method displayName(String) like this outside onCreate()

public void displayName(final  String name){

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

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

         }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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