无法将数据从JSONObject结果传递给ListView

时间:2018-03-01 14:47:40

标签: android android-volley

我是使用PHP和MySQL开发Android应用程序的新手,我目前正在使用Volley的简单CRUD指南。我碰到了一些我无法使用JSONObject结果填充ListView的东西。我已经检查过我的应用程序是否得到了api的结果,它仍然没有在ListView上显示任何内容

JSONObject结果

enter image description here

这是我的代码

 private void loadLogList(){
        StringRequest stringRequest = new StringRequest(Request.Method.GET, JSON_URL,
                new Response.Listener<String>() {

                    public void onResponse(String response){
                        try{
                            JSONObject obj = new JSONObject(response);
                            JSONArray logsArray = obj.getJSONArray("logs");
                            System.out.print("Object :" +obj);

                            for(int i = 0;i < logsArray.length();i++){
                                JSONObject logObject = logsArray.getJSONObject(i);

                                LogsModel model = new LogsModel(logObject.getString("date"),
                                        logObject.getString("time_in"),
                                        logObject.getString("time_out"),
                                        logObject.getString("division"),
                                        logObject.getString("department"),
                                        logObject.getString("designation"),
                                        logObject.getString("log_content"));

                                        logList.add(model);
                            }
                            LogsAdapter adapter = new LogsAdapter(logList,getApplicationContext());
                            lv.setAdapter(adapter);

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

                },
                new Response.ErrorListener(){
                    @Override
                    public void onErrorResponse(VolleyError error){
                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

这是我的ListView适配器

public class LogsAdapter extends ArrayAdapter<LogsModel> {
private List<LogsModel> logList;

private Context context;

public LogsAdapter(List<LogsModel> logList, Context context){
    super(context,R.layout.layout,logList);
    this.logList = logList;
    this.context = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
    LayoutInflater inflater = LayoutInflater.from(context);

    View listViewItem = inflater.inflate(R.layout.layout,null,true);

    TextView txtDate = (TextView) listViewItem.findViewById(R.id.txtDate);
    TextView txtTimeIn  = (TextView) listViewItem.findViewById(R.id.txtTimeIn);
    TextView txtTimeOut  = (TextView) listViewItem.findViewById(R.id.txtTimeOut);
    TextView txtDivision  = (TextView) listViewItem.findViewById(R.id.txtDivision);
    TextView txtDesignation  = (TextView) listViewItem.findViewById(R.id.txtDesignation);
    TextView txtDepartment  = (TextView) listViewItem.findViewById(R.id.txtDepartment);
    TextView txtActivities = (TextView) listViewItem.findViewById(R.id.txtActivities);

    LogsModel logs = logList.get(position);

    txtDate.setText(logs.getDate());
    txtTimeIn.setText(logs.getTime_in());
    txtTimeOut.setText(logs.getTime_out());
    txtDivision.setText(logs.getDivision());
    txtDesignation.setText(logs.getDesignation());
    txtDepartment.setText(logs.getDepartment());
    txtActivities.setText(logs.getLog_content());

    System.out.println("Model" +logs);
    return listViewItem;

}

1 个答案:

答案 0 :(得分:0)

首先用构造函数和getter创建一个类(在示例中是YourRecordHolderClass)来保存所有细节。然后将您的代码更改为:

import android.bluetooth.*;
import android.util.*;
import java.io.*;
import java.util.*;
import javax.obex.*;

public class BluetoothOPPHelper
{
    String address;
    BluetoothAdapter mBtadapter;
    BluetoothDevice device;
    ClientSession session;
    BluetoothSocket mBtSocket;
    protected final UUID OPPUUID=UUID.fromString(("00001105-0000-1000-8000-00805f9b34fb"));

    private String TAG="BluetoothOPPHelper";

public BluetoothOPPHelper(String address)
{
    mBtadapter=BluetoothAdapter.getDefaultAdapter();
    device=mBtadapter.getRemoteDevice(address);
    try
    {
        mBtSocket = device.createRfcommSocketToServiceRecord(OPPUUID);
    }
    catch (IOException e)
    {
        throw new RuntimeException(e);

    }
}
public ClientSession StartBatch(int n)
{
    ClientSession mSession = null;

    // TODO: Implement this method
    boolean retry=true;
    int times=0;
    while (retry && times < 4)
    {
        //BluetoothConnector.BluetoothSocketWrapper bttmp=null;
        try
        {
            mBtSocket.connect();
            //bttmp =  (new BluetoothConnector(device,false,BluetoothAdapter.getDefaultAdapter(),Arrays.asList(new UUID[]{OPPUUID,OPPUUID, OPPUUID}))).connect();//*/ device.createInsecureRfcommSocketToServiceRecord(OPPUUID);
            /*if(mBtSocket.isConnected())
             {
             mBtSocket.close();
             }*/
        }
        catch (Exception e)
        {
            Log.e(TAG, "opp fail sock " + e.getMessage());
            retry = true;
            times++;
            continue;
        }        

        try
        {
            //mBtSocket=bttmp.getUnderlyingSocket();
            //    mBtSocket.connect();
            BluetoothObexTransport mTransport = null;
            mSession = new ClientSession((ObexTransport)(mTransport = new BluetoothObexTransport(mBtSocket)));

            HeaderSet headerset = new HeaderSet();
            //    headerset.setHeader(HeaderSet.COUNT,n);

            headerset = mSession.connect(null);

            if (headerset.getResponseCode() == ResponseCodes.OBEX_HTTP_OK)
            {
                boolean mConnected = true;
            }
            else
            {
                Log.e(TAG, "SEnd by OPP denied;");
                mSession.disconnect(headerset);
                times++;
                continue;
            }

        }
        catch (Exception e)
        {
            Log.e(TAG, "opp failed;" , e);
            retry = true;
            times++;
            continue;
            //e.rintStackTrace();
        }
        retry=false;
    }
    return mSession;

}

protected boolean Put(ClientSession session, byte[] bytes, String as, String type)
{
    // TODO: Implement this method
    //byte [] bytes;
    String filename=as;
    boolean retry=true;
    int times=0;
    while (retry && times < 4)
    {        
        Operation putOperation=null;
        OutputStream mOutput = null;
        //ClientSession mSession = null;
        //ArrayUtils.reverse(bytes);
        try
        {    
            // Send a file with meta data to the server
            final HeaderSet hs = new HeaderSet();
            hs.setHeader(HeaderSet.NAME, filename);
            hs.setHeader(HeaderSet.TYPE, type);
            hs.setHeader(HeaderSet.LENGTH, new Long((long)bytes.length));
            Log.v(TAG,filename);
            //Log.v(TAG,type);
            Log.v(TAG,bytes.toString());
            putOperation = session.put(hs);

            mOutput = putOperation.openOutputStream();
            mOutput.write(bytes);
            mOutput.close();
            putOperation.close();
        }
        catch (Exception e)
        {
            Log.e(TAG, "put failed", e);
            retry = true;
            times++;
            continue;
            //e.printStackTrace();
        }
        finally
        {
            try
            {

                if(mOutput!=null)
                    mOutput.close();
                if(putOperation!=null)
                    putOperation.close();
            }
            catch (Exception e)
            {
                Log.e(TAG, "put finally" , e);
                retry = true;
                times++;
                continue;
            }
            //updateStatus("[CLIENT] Connection Closed");
        }
        retry = false;
        return true;
    }
    return false;
}

protected boolean Put(ClientSession s, OPPBatchInfo info)
{
    return Put(s,info.data,info.as,info.type);
}

private void FinishBatch(ClientSession mSession) throws IOException
{
    mSession.disconnect(null);
    try
    {
        Thread.sleep((long)500);
    }
    catch (InterruptedException e)
    {}
    mBtSocket.close();
}

public boolean flush() throws IOException
{
    if (sendQueue.isEmpty())
    {
        return true;
    }
    try
    {
        Thread.sleep((long)2000);
    }
    catch (InterruptedException e)
    {}
    ClientSession session=StartBatch(sendQueue.size());
    if (session == null)
    {
        return false;
    }
    while (!sendQueue.isEmpty())
    {
        if (Put(session, sendQueue.remove()) == false)
        {
            Log.e(TAG, "Put failed");
        }
    }
    FinishBatch(session);
    return true;
}
Queue<OPPBatchInfo> sendQueue;
public boolean AddTransfer(String as,String mimetype,byte[] data)
{
    return sendQueue.add(new OPPBatchInfo(as,mimetype,data));
}
class OPPBatchInfo
{
    String as;
    String type;
    byte[] data;
    public OPPBatchInfo(String as,String type,byte[] data)
        {
            this.as=as;
            this.data=data;
            this.type=type;
        }
    }
}

现在更改Adapter类中的构造函数:

    //Create string to keep your details
//String logObTimeIn; etc.
                            //Before "try" create ArrayList<HashMap<String, String>> location = null;
                            JSONObject obj = new JSONObject(response);
                            location = new ArrayList<>();
                            JSONArray logsArray = obj.getJSONArray("logs");
                            HashMap<String, String> map;

                            for(int i = 0;i < logsArray.length();i++){
                                JSONObject logObject = logsArray.getJSONObject(i);

                                map = new HashMap<>();
                                    map.put("date", logObject.getString("date"));
                                    map.put("time_in", logObject.getString("time_in")),
                                    map.put("time_out", logObject.getString("time_out")),
                                    map.put("division", logObject.getString("division")),
                                    map.put("department", logObject.getString("department")),
                                    map.put("designation", logObject.getString("designation")),
                                    map.put("log_content", logObject.getString("log_content"));
                                    location.add(map);
                            }

                            if(location != null){
                                for(i = 0; i < location.size(); i++){
                                    logObDate = location.get(i).get("date").toString();
                                    logObTimeIn = location.get(i).get("time_in").toString();
                                    logObTimeOut = location.get(i).get("time_out").toString();
                                    logObDivision = location.get(i).get("division").toString();
                                    logObDepartment = location.get(i).get("department").toString();
                                    logObDesignation = location.get(i).get("designation").toString();
                                    logObContent = location.get(i).get("log_content").toString();

                            //instead of xyz create ArrayList in your main class and call it here
                            //private ArrayList<YourRecordHolderClass> records = new ArrayList<>();
                            xyx.add(new YourRecordHolderClass(logObDate, logObTimeIn, logObTimeOut, logObDivision, logObDepartment, logObDesignation, logObContent));
                            listView = (ListView) view.findViewById(R.id.myListView);
                            LogsAdapter adapter = new LogsAdapter(records, getApplicationContext());
                            listView.setAdapter(adapter);
                            adapter.notifyDataSetChanged();
                            }
                        }

一切都应该没问题。让我知道它是如何工作的。