2
Personal I am new to programming for Android and I have a problem regarding a situation in an application I am developing using Gridview with an Adapter class and a list of items(object) coming from a webservice. I’d like your help.
Result of the Webservice bringing a list of patients with the following data: SUS Card and the Name. The SUS card has the function of identifying the patient, in the bank he and primary key.
Result from post JsonPost : 200 : {"paciente":
[{"cartaoSus":"123456789","nome":"Fábio"},
{"cartaoSus":"123456789111111","nome":"Teste"},
{"cartaoSus":"22222222222","nome":"Paulo"},{"cartaoSus":"33333333333","nome":"Maria"}]}
Leading
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.GridView;
import br.com.sistemaid.modelo.Adaptador;
import br.com.sistemaid.modelo.Paciente;
import br.com.sistemaid.webservice.ClienteREST;
public class PrincipalActivity extends Activity {
GridView gv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_principal_grid);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
listarPacientesInternados();
}
public void listarPacientesInternados() {
ClienteREST cliREST = new ClienteREST();
gv = (GridView) this.findViewById(R.id.monitor_grid);
try {
ArrayList<Paciente> pacientesAtendidos = (ArrayList<Paciente>) cliREST
.ListarPacientes();
gv.setAdapter(new Adaptador(this, pacientesAtendidos));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.principal, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Adapter
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import br.com.sistemaid.R;
public class Adaptador extends BaseAdapter {
private Context context;
private ArrayList<Paciente> lista;
public Adaptador(Context context, ArrayList<Paciente> lista) {
this.context = context;
this.lista = lista;
}
@Override
public int getCount() {
return lista.size();
}
@Override
public Paciente getItem(int posicao) {
return lista.get(posicao);
}
@Override
public long getItemId(int posicao) {
return posicao;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
PacienteViewHolder pacienteVH = new PacienteViewHolder();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.activity_principal_grid, parent, false);
pacienteVH.nomePaciente = (TextView) convertView.findViewById(R.id.textView1);
convertView.setTag(pacienteVH);
} else {
pacienteVH = (PacienteViewHolder) convertView.getTag();
}
return convertView;
}
static class PacienteViewHolder {
TextView nomePaciente;
}
}
Layout da Activity
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF2552"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="br.com.sistemaid.PrincipalActivity" >
<GridView
android:id="@+id/monitor_grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:columnWidth="60dp"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp" >
</GridView>
</LinearLayout>
Layout of the row
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="br.com.sistemaid"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="14" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".PrincipalActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Making some modifications to the system and putting to printstacktrace, started to be displayed this error in logcat:
My function of returning the list of patients is
import java.util.ArrayList;
import java.util.List;
import br.com.sistemaid.modelo.Paciente;
import br.com.sistemaid.webservice.WebServiceCliente;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
public class PacienteControle {
private static final String URL_WS =
"http://192.168.1.106:8080/ID-WebService/paciente/";
public List<Paciente> listarPacientes() throws Exception {
String[] resposta = new WebServiceCliente().get(URL_WS
+ "listarPacientes");
if (resposta[0].equals("200")) {
Gson gson = new Gson();
List<Paciente> listaPacientes = new ArrayList<Paciente>();
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(resposta[1]).getAsJsonArray();
for (int i = 0; i < array.size(); i++) {
listaPacientes.add(gson.fromJson(array.get(i), Paciente.class));
}
return listaPacientes;
} else {
throw new Exception(resposta[1]);
}
}
}
In the current situation the tablet screen appears blank. Any suggestion of what to do??
Adaptor class after corrections:
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import br.com.sistemaid.R;
public class Adaptador extends BaseAdapter {
private Context context;
private ArrayList<Paciente> lista;
public Adaptador(Context context, ArrayList<Paciente> lista) {
this.context = context;
this.lista = lista;
}
@Override
public int getCount() {
return lista.size();
}
@Override
public Paciente getItem(int posicao) {
return lista.get(posicao);
}
@Override
public long getItemId(int posicao) {
return posicao;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
PacienteViewHolder pacienteVH = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.item_grade, parent, false);
pacienteVH = new PacienteViewHolder();
pacienteVH.nomePaciente = (Button) convertView.findViewById(R.id.button1);
convertView.setTag(pacienteVH);
} else {
pacienteVH = (PacienteViewHolder) convertView.getTag();
}
pacienteVH.nomePaciente.setText(lista.get(position).getNomePaciente());
return convertView;
}
static class PacienteViewHolder {
Button nomePaciente;
}
}
List methodPatient
public List<Paciente> listarPacientes() throws Exception {
String[] resposta = new WebServiceCliente().get(URL_WS
+ "listarPacientes");
if (resposta[0].equals("200")) {
Gson gson = new Gson();
ArrayList<Paciente> listaPacientes = new ArrayList<Paciente>();
JsonParser parser = new JsonParser();
JsonArray jArray = (JsonArray) parser.parse(resposta[1]).getAsJsonObject().get("paciente");
for (int i = 0; i < jArray.size(); i++) {
listaPacientes.add(gson.fromJson(jArray.get(i), Paciente.class));
}
return listaPacientes;
} else {
throw new Exception(resposta[1]);
}
}
How to make this method work?
gv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getParent(), ((Button) v.findViewById(R.id.button1)).getText(),
Toast.LENGTH_SHORT);
}
});
Since this variable v he simply does not know.
Fabio, the problem is that the Webservice JSON is not an array, as the error says. In it you have an object whose only property is the array. You’d have to do:
parser.getAsJsonObject().getAsJsonArray("paciente")
.– Wakim
I made this change and the JSON error is no longer displayed. However gridView is still empty, without displaying the data. To check if the object was not null after this conversion I put to appear in the log the data and they are displayed correctly, all patients registered in the database are present.
– Fábio Luciano
After making the appropriate changes and with a little more search. I was able to solve the problem. I noticed that I also had not instantiated the patientVH and that Inflate had placed the reference for the wrong layout. I made an edit on the question to post the new codes. But there is another problem after the mounted grid I am not able to assemble the code for the effect of triggering the grid item that I switched to a button instead of a textView. Any recommendation to find the solution?
– Fábio Luciano