JSON数据未显示,而是显示空白屏幕 [英] JSON Data is not showing, rather showing blank screen

查看:181
本文介绍了JSON数据未显示,而是显示空白屏幕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图制作一个简单的应用程序,它将从服务器获取JSON数据并将其显示在自定义列表中,这很简单.

但是当我运行该应用程序时,它显示白色空白屏幕,但没有数据.它也没有显示任何错误,我假设如果有任何错误,它将不会在我的手机中运行.但不显示获取的数据.

这是MainActivity

package com.example.root.employeedata;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import org.json.JSONArray;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    List list  = new ArrayList<String>();
    String[] employees = new String[list.size()];
    String data = "";

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

        try{
            URL url = new URL("http://anontech.info/courses/cse491/employees.json");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            while(line != null){
                line = bufferedReader.readLine();
                data = data + line;
            }

            JSONArray array = new JSONArray(data);
            for(int i=0; i<array.length(); i++){
                String employeeName = array.getJSONObject(i).getString("name");
                list.add(employeeName);
            }

            for(int i=0; i<employees.length; i++){
                employees[i] = list.get(i).toString();
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }

        for(int i=0; i<employees.length; i++){
            System.out.println(employees[i]);
        }

        ListView listView = (ListView) findViewById(R.id.listView);
        CustomAdapter customAdapter = new CustomAdapter();
        listView.setAdapter(customAdapter);
    }

    class CustomAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return employees.length;
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            view = getLayoutInflater().inflate(R.layout.customlayout,null);

            TextView textView = (TextView)view.findViewById(R.id.employeeName);
            textView.setText(employees[i]);

            return view;
        }
    }
}

这是activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.root.employeedata.MainActivity">


    <ListView
        android:id="@+id/listView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

   </android.support.constraint.ConstraintLayout>

这是自定义列表的customlayout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <TextView
        android:id="@+id/employeeName"
        android:layout_width="wrap_content"
        android:layout_height="69dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_weight="1"
        android:text="TextView" />

</RelativeLayout>

这是AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.root.employeedata">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission 
    android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" 
        />
            </intent-filter>
       </activity>
       </application>
  </manifest>

这是运行该应用程序时显示的内容,

我发现的其他问题与我的问题不匹配,否则不会添加此问题.

解决方案

您正在MainThread上进行网络请求.您可能会遇到异常,但catch块会掩盖它.

 catch (Exception e){
            e.printStackTrace();
        }

您需要使用 AsyncTask 发出网络请求. /p>

类似这样的事情.创建一个内部类:

private class GetJsonTask extends AsyncTask<URL, Void, String> {
     protected String doInBackground(URL... urls) {
         try{
            HttpURLConnection httpURLConnection = (HttpURLConnection) urls[0].openConnection();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            while(line != null){
                line = bufferedReader.readLine();
                data = data + line;
            }
            return data;

        }
        catch (Exception e){
            e.printStackTrace();

        }
        return null;
     }



     protected void onPostExecute(String result) {
         if(result!=null){
         JSONArray array = new JSONArray(result);
            for(int i=0; i<array.length(); i++){
                String employeeName = array.getJSONObject(i).getString("name");
                list.add(employeeName);
            }
         }
     }
 }

Trying to make a simple app that will fetch JSON data from a server and show them in a custom List, pretty simple stuff.

But when I'm running the app, it is showing white blank screen but no data. It doesn't show any error either, I assume if there were any error it wouldn't be running in my phone. But doesn't show the fetched data.

Here is the MainActivity class

package com.example.root.employeedata;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import org.json.JSONArray;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    List list  = new ArrayList<String>();
    String[] employees = new String[list.size()];
    String data = "";

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

        try{
            URL url = new URL("http://anontech.info/courses/cse491/employees.json");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            while(line != null){
                line = bufferedReader.readLine();
                data = data + line;
            }

            JSONArray array = new JSONArray(data);
            for(int i=0; i<array.length(); i++){
                String employeeName = array.getJSONObject(i).getString("name");
                list.add(employeeName);
            }

            for(int i=0; i<employees.length; i++){
                employees[i] = list.get(i).toString();
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }

        for(int i=0; i<employees.length; i++){
            System.out.println(employees[i]);
        }

        ListView listView = (ListView) findViewById(R.id.listView);
        CustomAdapter customAdapter = new CustomAdapter();
        listView.setAdapter(customAdapter);
    }

    class CustomAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return employees.length;
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            view = getLayoutInflater().inflate(R.layout.customlayout,null);

            TextView textView = (TextView)view.findViewById(R.id.employeeName);
            textView.setText(employees[i]);

            return view;
        }
    }
}

Here is the activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.root.employeedata.MainActivity">


    <ListView
        android:id="@+id/listView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

   </android.support.constraint.ConstraintLayout>

Here is the customlayout.xml for custom list,

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <TextView
        android:id="@+id/employeeName"
        android:layout_width="wrap_content"
        android:layout_height="69dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_weight="1"
        android:text="TextView" />

</RelativeLayout>

Here is the AndroidManifest.xml,

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.root.employeedata">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission 
    android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" 
        />
            </intent-filter>
       </activity>
       </application>
  </manifest>

This is what it is showing when running the app,

The other questions that I have found did not match with my problem, otherwise would not be adding this question.

解决方案

You're doing a network request on the MainThread. You're probably getting an exception but it's getting masked by the catch block.

 catch (Exception e){
            e.printStackTrace();
        }

You need to use an AsyncTask to make your network requests.

Something like this. Create an inner class:

private class GetJsonTask extends AsyncTask<URL, Void, String> {
     protected String doInBackground(URL... urls) {
         try{
            HttpURLConnection httpURLConnection = (HttpURLConnection) urls[0].openConnection();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line = "";
            while(line != null){
                line = bufferedReader.readLine();
                data = data + line;
            }
            return data;

        }
        catch (Exception e){
            e.printStackTrace();

        }
        return null;
     }



     protected void onPostExecute(String result) {
         if(result!=null){
         JSONArray array = new JSONArray(result);
            for(int i=0; i<array.length(); i++){
                String employeeName = array.getJSONObject(i).getString("name");
                list.add(employeeName);
            }
         }
     }
 }

这篇关于JSON数据未显示,而是显示空白屏幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆