如何使用来自不同json

时间:2018-06-28 08:07:41

标签: android json listview urlretrieve

我正在开发一个应用程序,在该应用程序中,我需要从两个不同的json检索数据,并且必须在android中填充一个listview。在第一个Json中,我有一个对象数组,我有id对象和一个需要检索该对象数据的URL。

我该怎么做?我可以检索该对象并用该对象填充listview,但是我不知道如何获取单个对象的数据并在同一行中显示它。

列表视图应如下所示:

enter image description here

这是Json1:

[
    {
        "id": "S1",
        "url": "MyUrl1"
    },
    {
        "id": "S2",
        "url": "MyUrl2"
    },
    {
        "id": "S3",
        "url": "MyUrl3"
    }
]

每个对象都不同。这是Json2:

{
    "id": "S1",
    "temp": "20.03",
    "time": "28 June 2018, 9:12:13"
}

因此,我可以检索id并在listView中显示所有id对象,但不能为每个对象检索“ temp”和“ time”值。

这是我的代码:

适配器

public class SensorAdapter extends BaseAdapter{
ArrayList<String> id= new ArrayList<String>();
ArrayList<String> labelno_array = new ArrayList<String>();
Context context;
LayoutInflater inflater;


public SensorAdapter2(Context c, ArrayList<String> label_array)
{
    context = c;
    id= label_array;
   // temp=temp_array;
   // time=time_array;
    //labelno_array = no_array;
    inflater = LayoutInflater.from(context);
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return id.size();
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return position;
}

@Override
public long getItemId(int position)
{
    // TODO Auto-generated method stub
    return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    View v = convertView;
    Holder holder;
    // TODO Auto-generated method stub
    if (v == null) {
        v = inflater.inflate(R.layout.columns_sensor, null);
        holder = new Holder();
        holder.tv_labelname = (TextView)v.findViewById(R.id.idsensor);

        v.setTag(holder);
    } else {
        holder = (Holder) v.getTag();
    }


    holder.tv_labelname.setText(id.get(position));

    return v;
}
public class Holder
{
    TextView tv_labelname,tv_labelno, tv_temp, tv_time;
}

这是我用来检索传感器数量的代码:

代码

 class RetrieveFeedTask2 extends AsyncTask<Void, Void, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }



    protected String doInBackground(Void... urls) {
        String API_URL = "MyUrl";

        try {
            URL url = new URL(API_URL);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            try {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line).append("\n");
                }
                bufferedReader.close();
                return stringBuilder.toString();
            }
            finally{
                urlConnection.disconnect();
            }
        }
        catch(Exception e) {
            Log.e("ERROR", e.getMessage(), e);
            return null;
        }
    }

    protected void onPostExecute(String response) {
        if(response == null) {
            response = "THERE WAS AN ERROR";
        }
        //            progressBar.setVisibility(View.GONE);
        Log.i("INFO", response);

        try
        {

            JSONArray array=new JSONArray(response);

            for(int i = 0; i < array.length(); i++)
            {
                JSONObject obj = array.getJSONObject(i);

                String mysenso=obj.getString("id");
                String myurl=obj.getString("url");
                //partire nuova chiamata con l'url.
                label_no.add(myurl);
                label_name.add(mysenso);


            }


        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }
        SensorAdapter2 adapter = new SensorAdapter2(Principale.this, label_name);
        listView.setAdapter(adapter);


    }

}

那么,如何连接对象URL并更新同一行中该对象的数据?

2 个答案:

答案 0 :(得分:0)

首先,创建两个这样的POJO

  

First.java

public class First {
    String id,url;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}
  

Second.java

public class Second{
    String id,temp,time;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTemp() {
        return temp;
    }

    public void setTemp(String temp) {
        this.temp = temp;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }
}

然后在您的asynctask中 RetrieveFeedTask2类扩展了AsyncTask {

@Override
protected void onPreExecute() {
    super.onPreExecute();
}



protected String doInBackground(Void... urls) {
    String API_URL = "MyUrl";

    try {
        URL url = new URL(API_URL);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
            bufferedReader.close();
            return stringBuilder.toString();
        }
        finally{
            urlConnection.disconnect();
        }
    }
    catch(Exception e) {
        Log.e("ERROR", e.getMessage(), e);
        return null;
    }
}

protected void onPostExecute(String response) {
    if(response == null) {
        response = "THERE WAS AN ERROR";
    }
    //            progressBar.setVisibility(View.GONE);
    Log.i("INFO", response);
     ArrayList<First> firstList = new ArrayList<>();
    try
    {

        JSONArray array=new JSONArray(response);

        for(int i = 0; i < array.length(); i++)
        {
            JSONObject obj = array.getJSONObject(i);

            String mysenso=obj.getString("id");
            String myurl=obj.getString("url");
            First first = new First();
            first.setId(mysenso);
            first.setUrl(myurl);
            firstList.add(first);

        }


    }
    catch (JSONException e)
    {
        e.printStackTrace();
    }
    SensorAdapter2 adapter = new SensorAdapter2(Principale.this, firstList);
    listView.setAdapter(adapter);


}

}

然后在您的适配器中

public class SensorAdapter extends BaseAdapter{
ArrayList<FirstList> firstList;

Context context;
LayoutInflater inflater;


public SensorAdapter2(Context c, ArrayList<FirstList> firstList)
{
    context = c;
    this.firstList=firstList;
   // temp=temp_array;
   // time=time_array;
    //labelno_array = no_array;
    inflater = LayoutInflater.from(context);
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return firstList.size();
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return position;
}

@Override
public long getItemId(int position)
{
    // TODO Auto-generated method stub
    return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    View v = convertView;
    Holder holder;
    // TODO Auto-generated method stub
    if (v == null) {
        v = inflater.inflate(R.layout.columns_sensor, null);
        holder = new Holder();
        holder.tv_labelname = (TextView)v.findViewById(R.id.idsensor);

        v.setTag(holder);
    } else {
        holder = (Holder) v.getTag();
    }


    holder.tv_labelname.setText(firstList.get(position).getId());

    return v;
}
public class Holder
{
    TextView tv_labelname,tv_labelno, tv_temp, tv_time;
}

这样,您的第一部分就是设置。现在,您需要获取被单击项的值,然后从那里获取url,然后将该URL传递给另一个asyntask,并在Second.java类中设置其值,然后从那里显示它。 要获取被单击的项目,您需要在findViewById-listview所在的类中使用以下代码。

listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
        String url = (String) listView.getItemAtPosition(position);
        Toast.makeText(this,"You selected : " + url,Toast.LENGTH_SHORT).show();         
//here you will get the url and then now send it to another asynctask and parse it and set the value to Second.java and start another activity or fragment to display data from Second.java


    }
});

答案 1 :(得分:0)

如果在您的情况下,我将首先检索数据(如果数据量很小),然后担心显示它们。

如果数据很大,我将尝试在查看数据的同时检索额外的信息

所以让我们继续吧。

提示:我假设您已经知道如何获取数据(基于'RetrieveFeedTask2类-尽管您可能应该在返回之前断开连接)

一般情况:

在所有情况下都需要
1.一堂课

class MyObject {
   String id,time,temp,url;
}

2。一种获取您的First JSON并将其存储在列表中的方法

public List&#60;MyObject&#62; fetchThenParseIntoList() {
   . . .
}

现在您将使用它来获取第一个JSON并将其解析为列表

List&#60;MyObject&#62; myObjects = fetchThenParseIntoList()

因此,现在您将拥有仅包含ID和网址的“ MyObject”对象列表

3.可以被赋予对象以获取该对象额外信息的线程。说

class ExtraInfoThread extends Thread {
    private MyObject myObject;
    public ExtraInfoThread(final MyObject myObject) {
        this.myObject = myObject
    }

    @Override
    public void run() {
        . . .
    }
}

案例1:小数据(说少于1000个对象)

环绕每个对象并获取额外的信息

for(MyObject myObject: myObjects) {
    new ExtraInfoThread(myObject).start()
}

现在您有了一个包含所有数据的对象,并且可以根据需要显示它

情况2:大数据

仅在尝试显示该线程时,调用该线程以获取其他信息

public View getView() {
  new ExtraInfoThread(myObject).start()
  . . .
}

如果您可以实现JSON的视图和获取功能,那么您将毫无顾忌地实现所需的功能