Criação de JSON para comunicação HTTP

  • Respostas:1
Evanderson Pimentel
  • Posts no fórum: 2

09/09/2015, 21:26:55 via Web

Criei um app que enviar e recebe dados para um servido.

mas está aparecendo o seguinte erro no logcat, alguem pode me ajudar?

   public class SistemaFacade
{
  private static SistemaFacade sistemaFacade = new SistemaFacade();

  private List<Device> devices;
  RequestConfig globalConfig = RequestConfig.custom()
            .setCookieSpec(CookieSpecs.BEST_MATCH)
            .build();
  CloseableHttpClient httpClient;
  private Integer idDevice;
  private String idUser;
  private boolean logged;
  private String mensagem;
  private String urlBase;

  public SistemaFacade()
  {
    this.httpClient = HttpClients.custom()
            .setDefaultRequestConfig(globalConfig)
            .build();
    this.urlBase = "URL";
    this.idUser = null;
    this.devices = new ArrayList<Device>();
    this.logged = false;
    this.mensagem = null;
  }


  public static SistemaFacade getSistemaFacade()
  {
    return sistemaFacade;
  }

  private String readResponse(HttpResponse paramHttpResponse)
  {
    try
    {
      String str = EntityUtils.toString(paramHttpResponse.getEntity());
      return str;
    }
    catch (ParseException localParseException)
    {
      localParseException.printStackTrace();
      return null;
    }
    catch (IOException localIOException)
    {
      while (true)
        localIOException.printStackTrace();
    }
  }

  public List<Device> getDevices()
  {
      List<Device> lista = new ArrayList<SistemaFacade.Device>();
      lista.addAll(this.devices);
      return lista;
  }

  public String getIdUser()
  {
    return this.idUser;
  }

  public String getMensagem()
  {
    String str = this.mensagem;
    this.mensagem = null;
    return str;
  }

  public boolean isLogged()
  {
    return this.logged;
  }

  @SuppressWarnings({"unchecked","rawtypes"})
  public boolean login(String paramString1, String paramString2)
  {
    try
    {
      HttpPost localHttpPost = new HttpPost(this.urlBase + "/appmob/login");
      List params = new ArrayList();
      params.add(new BasicNameValuePair("login", paramString1));
      params.add(new BasicNameValuePair("password", paramString2));
      localHttpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
      String str = readResponse(this.httpClient.execute(localHttpPost));
      if (str == null);
      while (true)
      {
        try
        {
          JSONObject jsonObject = new JSONObject(str);
          if (jsonObject.getInt("retorno") == -1)
          {
            if (!jsonObject.has("mensagem"))
              continue;
            setMensagem(jsonObject.getString("mensagem"));
            return false;
          }
          setIdUser(jsonObject.getString("id_user"));
          this.logged = true;
          return true;
        }
        catch (JSONException localJSONException)
        {
          localJSONException.printStackTrace();
          return false;
        }
      }
    }
    catch (ClientProtocolException localClientProtocolException)
    {
        setMensagem("Problemas na conexão com o servidor");
        return false;
    }
    catch (IOException localIOException)
    {
      setMensagem("Problemas na conexão com o servidor");
    }
    return false;
  }

  public void logout()
  {
    sistemaFacade = new SistemaFacade();
  }

  @SuppressWarnings({ "rawtypes", "unchecked" })
  public void setDevices(List<Device> paramList)
  {
      ArrayList localArrayList = new ArrayList();
      localArrayList.addAll(paramList);
      this.devices = localArrayList;
  }

  public void setIdUser(String paramString)
  {
    this.idUser = paramString;
  }

  public void setMensagem(String paramString)
  {
    this.mensagem = paramString;
  }

  @SuppressLint("SimpleDateFormat")
@SuppressWarnings({ "rawtypes", "unchecked" })
public boolean updateDevices()
  {
      if (!isLogged())
        return false;

      try
      {
        HttpPost localHttpPost = new HttpPost(this.urlBase + "/appmob/updateDevices");
          if (this.idDevice != null)
          {
            ArrayList localArrayList1 = new ArrayList();
            // parece que ele quer atualizar somente um device por vez
            localArrayList1.add(new BasicNameValuePair("id_device", this.idDevice.toString()));
            localHttpPost.setEntity(new UrlEncodedFormEntity(localArrayList1, "UTF-8"));
          }
        String str = readResponse(this.httpClient.execute(localHttpPost));
        if (str == null)
          return false;

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        try
        {
          JSONArray jsonArray = new JSONArray(str);
          List<Device> list = new ArrayList<Device>();
          for (int i = 0; i < jsonArray.length(); i++)
          {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                Device device = new Device();
                if (jsonObject.has("devices_id"))
                  device.device_id = Integer.parseInt(jsonObject.getString("devices_id"));
                if (jsonObject.has("name"))
                  device.name = jsonObject.getString("name");
                 if (jsonObject.has("car_modelo"))
                  device.car_modelo = jsonObject.getString("car_modelo");
                if (jsonObject.has("car_placa"))
                  device.car_placa = jsonObject.getString("car_placa");
                 if (jsonObject.has("chip"))
                  device.chip = jsonObject.getString("chip");
                if (jsonObject.has("obs"))
                  device.obs = jsonObject.getString("obs");
                if (jsonObject.has("icone"))
                  device.icone = jsonObject.getString("icone");
                if (jsonObject.has("uniqueId"))
                  device.uniqueId = jsonObject.getString("uniqueId");

                if (jsonObject.has("latestPosition_id"))
                  device.latestPosition_id = Integer.parseInt(jsonObject.getString("latestPosition_id"));
                if (jsonObject.has("longitude"))
                  device.longitude = Float.parseFloat(jsonObject.getString("longitude"));
                if (jsonObject.has("latitude"))
                  device.latitude = Float.parseFloat(jsonObject.getString("latitude"));
                if (jsonObject.has("speed"))
                  device.speed = Float.parseFloat(jsonObject.getString("speed"));
                if (jsonObject.has("status"))
                  device.status = jsonObject.getString("status");
                try {
                if (jsonObject.has("time"))
                  device.time = jsonObject.getLong("time") * 1000;
                }catch(Exception e) {continue;}

                if (jsonObject.has("address"))
                  device.address = jsonObject.getString("address");



                list.add(device);
          }
          setDevices(list);
          return true;
        }
        catch (JSONException localJSONException)
        {
          localJSONException.printStackTrace();
          return false;
        }
      }
      catch (ClientProtocolException localClientProtocolException)
      {
        localClientProtocolException.printStackTrace();
        return false;
      }
      catch (IOException localIOException)
      {
        localIOException.printStackTrace();
      }
      return false;
  }

  public Integer getIdDevice() {
    return idDevice;
}

public void setIdDevice(Integer idDevice) {
    this.idDevice = idDevice;
}

public class Device
  {
    // dados da tabela devices
    int device_id;          
    String name;
    String uniqueId;
    int latestPosition_id;  
    int grupo_id;           
    String car_modelo;      
    String car_placa;       
    String chip;
    String obs;
    String icone;          
    String address;
    float latitude;         
    float longitude;        
    float speed;
    long time; 
    String status; 
   public Device()

    {
    }
  }
}

E

public class LoginAsyncTask extends AsyncTask<String, Void, Boolean>

{

@Override
protected Boolean doInBackground(String... arg0) {
    return Boolean.valueOf(SistemaFacade.getSistemaFacade().login(arg0[0], arg0[1]));
}

}

Responder
Evanderson Pimentel
  • Posts no fórum: 2

09/09/2015, 21:27:38 via Web

esqueci o logcat rsrsrs

09-09 18:33:37.946: W/AudioTrack(348): AUDIO_OUTPUT_FLAG_FAST denied
by client 09-09 18:33:38.727: W/System.err(991):
org.json.JSONException: Value cannot be converted to JSONObject 09-09 18:33:38.728:
W/System.err(991): at org.json.JSON.typeMismatch(JSON.java:111) 09-09
18:33:38.729: W/System.err(991): at
org.json.JSONObject.(JSONObject.java:160) 09-09 18:33:38.729:
W/System.err(991): at org.json.JSONObject.(JSONObject.java:173)
09-09 18:33:38.729: W/System.err(991): at
com.rastreamentoquarkgps.SistemaFacade.login(SistemaFacade.java:117)
09-09 18:33:38.729: W/System.err(991): at
com.rastreamentoquarkgps.LoginAsyncTask.doInBackground(LoginAsyncTask.java:10)
09-09 18:33:38.729: W/System.err(991): at
com.rastreamentoquarkgps.LoginAsyncTask.doInBackground(LoginAsyncTask.java:1)
09-09 18:33:38.729: W/System.err(991): at
android.os.AsyncTask$2.call(AsyncTask.java:288) 09-09 18:33:38.729:
W/System.err(991): at
java.util.concurrent.FutureTask.run(FutureTask.java:237) 09-09
18:33:38.730: W/System.err(991): at
android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 09-09
18:33:38.730: W/System.err(991): at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
09-09 18:33:38.730: W/System.err(991): at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
09-09 18:33:38.730: W/System.err(991): at
java.lang.Thread.run(Thread.java:818)

Responder