JSON数据未显示,而是显示空白屏幕

时间:2018-06-20 12:14:44

标签: java android 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>

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

enter image description here

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

3 个答案:

答案 0 :(得分:2)

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

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

您需要使用AsyncTask发出网络请求。

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

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

答案 1 :(得分:1)

这是因为您的员工的字符串数组大小为0。

List list  = new ArrayList<String>();//initially it has 0 size 
String[] employees = new String[list.size()];//list.size()==0

将雇员的String []转换为Arraylist将解决您的问题。

ArrayList<String> employees = new ArrayList<String>();

详细信息 看到这段代码

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

因为employees.length为0,所以即使对于单个项目,您的循环基本上也不起作用。

答案 2 :(得分:0)

1-确保服务器连接逻辑远离UI线程,可以使用AsyncTask之类的东西。

// Make server logic inside Async Task.
    new AsyncTaskHandler(new OnFinishCallback() {
        @Override
        public void onSuccess(List<String> result) {
            CustomAdapter customAdapter = new CustomAdapter(result);
            listView.setAdapter(customAdapter);
        }
    }).execute("http://anontech.info/courses/cse491/employees.json");

2。避免匿名AsyncTask内存泄漏static inner AsyncTask

/**
 * Static inner class to handle memory leak with inner class.
 */
public static class AsyncTaskHandler extends AsyncTask<String, Void, List<String>> {
    private final OnFinishCallback callback;
    public AsyncTaskHandler(OnFinishCallback callback) {
        this.callback = callback;
    }
.....
}

3-更新UI线程内的UI组件ListView,在UI线程下执行AsyncTask方法onPostExecute,可以在{{1}之后使用OnFinishCallback更新列表适配器}被叫。

onPostExecute

4-使用RecyclerView代替 @Override protected void onPostExecute(List<String> result) { // Executed under UI thread to update UI component. callback.onSuccess(result); } 或至少使用ListView模式Making ListView Scrolling Smooth

ViewHolder

5-完整示例。

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            final ViewHolder viewHolder;
        .....
        }
相关问题