我是业余Andriod程序员,我的应用程序在列表视图中显示JSON字符串。这是JSON对象:
{"datos":[{"TITULO":"PRUEBA1","NOMBRELINEA":"CORTE CABALLERO","MONTO":"12.84"},
{"TITULO":"PRUEBA1","NOMBRELINEA":"SECADO","MONTO":"8.56"},
{"TITULO":"PRUEBA1","NOMBRELINEA":"PEINADO CABALLERO","MONTO":"0"},
{"TITULO":"PRUEBA2","NOMBRELINEA":"LAVADO KERAS","MONTO":"7.49"},
{"TITULO":"PRUEBA2","NOMBRELINEA":"MASCARA KERAS","MONTO":"10.70"},
{"TITULO":"PRUEBA3","NOMBRELINEA":"MECHAS CORTO","MONTO":"6.42"},
{"TITULO":"PRUEBA3","NOMBRELINEA":"MECHAS LARGO","MONTO":"10"}]}
我设法使用简单的适配器和JSON解析器将JSON放入listview,结果可以在此图像上看到:
但是,我希望它看起来像这样:
我喜欢Cyril Mottier建议使用View类的visibility属性并在重复时设置GONE行,但他建议使用的代码是静态数据:
这是JSON Parser的代码:
public class JSONParser {
/** Recibe un JSONobject y retorna una lista */
public List<HashMap<String,String>> parse(JSONObject jObject){
JSONArray jDatos = null;
try {
/** Recupera todos los elementos en el arreglo 'datos' */
jDatos = jObject.getJSONArray("datos");
} catch (JSONException e) {
e.printStackTrace();
}
/** Invoking getCountries with the array of json object
* where each json object represent a country
*/
return getDatos(jDatos);
}
private List<HashMap<String, String>> getDatos(JSONArray jDatos){
int datoCount = jDatos.length();
List<HashMap<String, String>> datoList = new ArrayList<HashMap<String,String>>();
HashMap<String, String> dato = null;
/** Taking each country, parses and adds to list object */
for(int i=0; i<datoCount;i++){
try {
/** Call getCountry with country JSON object to parse the country */
dato = getDato((JSONObject)jDatos.get(i));
datoList.add(dato);
} catch (JSONException e) {
e.printStackTrace();
}
}
return datoList;
}
/** Parsing the JSON object */
private HashMap<String, String> getDato(JSONObject jDato){
HashMap<String, String> dato = new HashMap<String, String>();
String nombre = "";
String precio="";
String tipo="";
try {
tipo = jDato.getString("TITULO");
nombre = jDato.getString("NOMBRELINEA");
precio = jDato.getString("MONTO");
dato.put("TITULO", tipo);
dato.put("NOMBRELINEA", nombre);
dato.put("MONTO", precio);
} catch (JSONException e) {
e.printStackTrace();
}
return dato;
}
}
这是主要活动:
public class MainActivity extends Activity {
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.l1);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
}
private String xHttpPost(String targetURL, String Variable, String Valor){
String urlParameters = "";
URL url;
HttpURLConnection connection = null;
try {
//Crear parametros del post
urlParameters = Variable + "=" + URLEncoder.encode(Valor, "UTF-8");
//Crear conexion
url = new URL(targetURL);
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream (connection.getOutputStream());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
//Get Response
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
connection.disconnect();
return sb.toString();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
return e.toString();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
return e.toString();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
return e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
return e.toString();
}
}
public void onStart(){
super.onStart();
String Consulta = "SELECT lt.nombre AS titulo, LC.nombrecombo AS NombreLinea,(Select Sum(Precioventa1) as Precio from productos where Codigo in (Select IdProducto from listacombodetalle LCD where LCD.idcombo = Lc.Id)) as Monto FROM LISTATITULO LT, LISTACOMBO LC where Lt.id = Lc.idtitulo";
String Z = xHttpPost("http://192.168.1.2/android/api/ConsultarFbLP", "query", Consulta);
String Q = "{" + " \"datos\":" + Z + "}";
Toast.makeText(this, Q, Toast.LENGTH_LONG).show();
ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
listViewLoaderTask.execute(Q);
}
public class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{
JSONObject jObject;
/** Doing the parsing of xml data in a non-ui thread */
@Override
protected SimpleAdapter doInBackground(String... Q) {
try{
jObject = new JSONObject(Q[0]);
JSONParser JsonParser = new JSONParser();
JsonParser.parse(jObject);
}catch(Exception e){
Log.d("JSON Exception1",e.toString());
}
JSONParser jsonParser = new JSONParser();
List<HashMap<String, String>> datos = null;
try{
/** Getting the parsed data as a List construct */
datos = jsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
/** Keys used in Hashmap */
String[] from = {"TITULO","NOMBRELINEA","MONTO"};
/** Ids of views in listview_layout */
int[] to = {R.id.textViewT,R.id.textViewR,R.id.textViewP};
/** Instantiating an adapter to store each items
* R.layout.listview_layout defines the layout of each item
*/
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), datos, R.layout.lv_item, from, to);
return adapter;
}
/** Invoked by the Android system on "doInBackground" is executed completely */
/** This will be executed in ui thread */
@Override
protected void onPostExecute(SimpleAdapter adapter) {
/** Getting a reference to listview of main.xml layout file */
ListView listView = ( ListView ) findViewById(R.id.lv_datos);
/** Setting the adapter containing the country list to listview */
listView.setAdapter(adapter);
}
}
}
这是填充列表视图的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/textViewT"
android:layout_width="match_parent"
android:layout_height="75dp"
android:layout_weight=".6"
android:background="#f00"
android:gravity="left"
android:text="Tipo de servicio"
android:textColor="#fff"
android:textSize="60sp"
android:visibility="visible"/>
<TextView
android:id="@+id/textViewR"
android:layout_width="500dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textViewT"
android:text="Renglon"
android:textColor="#000"
android:textSize="40sp" />
<TextView
android:id="@+id/textViewP"
android:layout_width="300dp"
android:layout_height="50dp"
android:layout_alignBaseline="@+id/textViewR"
android:layout_alignBottom="@+id/textViewR"
android:layout_toRightOf="@+id/textViewR"
android:background="#BABABF"
android:gravity="center"
android:text="Precio"
android:textColor="#000"
android:textSize="40sp" />
</RelativeLayout>
有关如何隐藏重复行的任何建议?对于这些链接感到抱歉,我很新。
提前致谢!