Ir para conteúdo
  • ×   Você colou conteúdo com formatação.   Remover formatação

      Only 75 emoji are allowed.

    ×   Your link has been automatically embedded.   Display as a link instead

    ×   Your previous content has been restored.   Clear editor

    ×   You cannot paste images directly. Upload or insert images from URL.

  • Conteúdo Similar

    • Por Leonardo Sandrini
      Eu criei duas classes customizadas de acordo com o que foi orientado por meu professor para fazer a requisição no servidor, mas estou recebendo um retorno 400 e não consigo descobrir a razão. Pesquisando, vi que pode ser algo relacionado ao cabeçalho, mas não sei como enviá-lo na minha requisição JSon customizada.
      Este é o código do meu do meu código customizado para requisição de JsonObject:
      package com.example.sandrini.pokeagenda; import com.android.volley.AuthFailureError; import com.android.volley.Response; import com.android.volley.RetryPolicy; import com.android.volley.toolbox.JsonObjectRequest; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; public class CustomJSONObjectRequest extends JsonObjectRequest { public CustomJSONObjectRequest(int method, String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) { super(method, url, jsonRequest, listener, errorListener); } @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<>(); headers.put("Content-Type", "application/json; charset=utf-8"); return headers; } @Override public RetryPolicy getRetryPolicy() { return super.getRetryPolicy(); } } Este é o código da minha Request Queue:
      package com.example.sandrini.pokeagenda; import android.content.Context; import com.android.volley.Cache; import com.android.volley.Network; import com.android.volley.RequestQueue; import com.android.volley.toolbox.BasicNetwork; import com.android.volley.toolbox.DiskBasedCache; import com.android.volley.toolbox.HurlStack; public class CustomVolleyRequestQueue { private static CustomVolleyRequestQueue mInstance; private static Context mCtx; private RequestQueue mRequestQueue; private CustomVolleyRequestQueue(Context context) { //recebe o contexto da aplicação //Assim a fila dura o ciclo de vida do app mCtx = context; mRequestQueue = getRequestQueue(); } public static synchronized CustomVolleyRequestQueue getmInstance(Context context) { if (mInstance == null) { mInstance = new CustomVolleyRequestQueue(context); } //retorna uma instância da fila return mInstance; } public RequestQueue getRequestQueue() { if (mRequestQueue == null) { //Cache 10MB Cache cache = new DiskBasedCache(mCtx.getCacheDir(), 10 *1024); Network network = new BasicNetwork(new HurlStack()); mRequestQueue = new RequestQueue(cache, network); mRequestQueue.start(); } return mRequestQueue; } } Este é o código da Activity onde estou tentando fazer a requisição:
      package com.example.sandrini.pokeagenda; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonRequest; import com.google.gson.Gson; import org.json.JSONException; import org.json.JSONObject; import java.util.EmptyStackException; public class CreateUserActivity extends AppCompatActivity implements Response.Listener, Response.ErrorListener { private static final String REQUEST_TAG = "CreateUser"; Trainer trainer = new Trainer(); EditText loginCreateInput, emailCreateInput, pwdCreateInput; Button createUserButton; private RequestQueue mQueue; JsonRequest jsonRequest; ProgressBar progressBarCreateUser; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_user); loginCreateInput = (EditText) findViewById(R.id.login_create_input); emailCreateInput = (EditText) findViewById(R.id.email_create_input); pwdCreateInput = (EditText) findViewById(R.id.pwd_create_input); createUserButton = (Button) findViewById(R.id.create_user_button); progressBarCreateUser = (ProgressBar) findViewById(R.id.progress_bar_create_user); progressBarCreateUser.setVisibility(View.INVISIBLE); } @Override protected void onStart() { super.onStart(); createUserButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (loginCreateInput.getText().toString().equals("")) { Toast.makeText(getApplicationContext(), "Please, set a login", Toast.LENGTH_SHORT).show(); } else if (emailCreateInput.getText().toString().equals("")) { Toast.makeText(getApplicationContext(), "Please, set an email", Toast.LENGTH_SHORT).show(); } else if (pwdCreateInput.getText().toString().equals("")) { Toast.makeText(getApplicationContext(), "Please, set a password", Toast.LENGTH_SHORT).show(); } else { String url = "http://192.168.25.6:8081/PokedexWS/webresources/pokews/poke/insert/trainer"; /*trainer.setUsername(loginCreateInput.getText().toString()); trainer.setEmail(emailCreateInput.getText().toString()); trainer.setPassword(pwdCreateInput.getText().toString());*/ trainer.setUsername("gato"); trainer.setEmail("gato"); trainer.setPassword("gato"); try { JSONObject jsonObject; Gson gson = new Gson(); String trainerToGson = gson.toJson(trainer); jsonObject = new JSONObject(trainerToGson); //String trainerToGson = "{\"username\":"+ "\"" + trainer.getUsername()+ "\"" + "," + //"\"email\":"+ "\"" + trainer.getEmail() + "\"" + "," + //"\"username\":"+ "\"" + trainer.getPassword()+ "\"" + "}"; //createUserButton.setText(trainerToGson); mQueue = CustomVolleyRequestQueue.getmInstance(CreateUserActivity.this.getApplicationContext()).getRequestQueue(); jsonRequest = new CustomJSONObjectRequest(Request.Method.POST, url, jsonObject, CreateUserActivity.this, CreateUserActivity.this); jsonRequest.getHeaders(); mQueue.add(jsonRequest); progressBarCreateUser.setVisibility(View.VISIBLE); } catch (Exception e) { e.printStackTrace(); } } } }); } @Override protected void onStop() { super.onStop(); if(mQueue != null) { mQueue.cancelAll(REQUEST_TAG); } } @Override public void onErrorResponse(VolleyError error) { progressBarCreateUser.setVisibility(View.INVISIBLE); Toast.makeText(getApplicationContext(), "Register failed", Toast.LENGTH_LONG).show(); Log.e("erro400", error.getMessage().toString()); Log.e("erro400", error.getCause().toString()); Log.e("erro400", error.getStackTrace().toString()); } @Override public void onResponse(Object trainerObject) { progressBarCreateUser.setVisibility(View.INVISIBLE); Toast.makeText(getApplicationContext(), "Registered successfully", Toast.LENGTH_LONG).show(); Intent intent = new Intent(CreateUserActivity.this, WelcomeTrainerActivity.class); startActivity(intent); finish(); } } Este é o meu Web Service:
      package ws; import com.google.gson.Gson; import dao.PokemonDAO; import dao.TrainerDAO; import java.util.ArrayList; import javax.ws.rs.core.Context; import javax.ws.rs.core.UriInfo; import javax.ws.rs.Produces; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PUT; import javax.ws.rs.PathParam; import javax.ws.rs.core.MediaType; import model.Pokemon; import model.Trainer; /** * REST Web Service * * @author sandrini */ @Path("pokews") public class PokedexWebService { PokemonDAO pokemonDAO = new PokemonDAO(); TrainerDAO trainerDAO = new TrainerDAO(); @Context private UriInfo context; /** * Creates a new instance of PokedexWebService */ public PokedexWebService() { } /** * Retrieves representation of an instance of teste.GenericResource * @return an instance of java.lang.String */ @GET @Produces(MediaType.APPLICATION_XML) public String getXml() { //TODO return proper representation object throw new UnsupportedOperationException(); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("poke/list") public ArrayList<Pokemon> pokeList() { return pokemonDAO.listPokemon(); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("poke/fetch/{id}") public Pokemon pokeFetch(@PathParam("id") int id) { return pokemonDAO.fetchPokemon(id); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("poke/isFavorite/{id}") public String pokeIsFavorite(@PathParam("id") int id) { return pokemonDAO.isFavorite(id); } @GET @Produces(MediaType.APPLICATION_JSON) @Path("poke/login/{login}/{pwd}") public Trainer pokelogin(@PathParam("login") String login, @PathParam("pwd") String pwd) { return trainerDAO.authUser(login, pwd); } @DELETE @Path("poke/delete/{id}") public boolean delete(@PathParam("id")int id) { return pokemonDAO.deletePokemon(id); } @POST @Consumes(MediaType.APPLICATION_JSON) @Path("poke/insert") public boolean pokeInsert(String content) { Gson gson = new Gson(); Pokemon pokemon = (Pokemon) gson.fromJson(content, Pokemon.class); return pokemonDAO.insertPokemon(pokemon); } @POST @Consumes(MediaType.APPLICATION_JSON) @Path("poke/insert/trainer") public boolean trainerInsert(String content) { Gson gson = new Gson(); Trainer trainer = (Trainer) gson.fromJson(content, Trainer.class); return trainerDAO.insertTrainer(trainer); } @PUT @Consumes(MediaType.APPLICATION_JSON) @Path("poke/update") public boolean pokeUpdate(String content) { Gson gson = new Gson(); Pokemon pokemon = (Pokemon) gson.fromJson(content, Pokemon.class); return pokemonDAO.updatePokemon(pokemon); } /** * PUT method for updating or creating an instance of GenericResource * @param content representation for the resource */ @PUT @Consumes(MediaType.APPLICATION_XML) public void putXml(String content) { } } Eu peguei um código java pra testar o WS e tá funcionando, só não estou conseguindo requisitar pelo android:
      package acessorest; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.lang.ProcessBuilder.Redirect.Type; import java.net.HttpURLConnection; import java.net.URL; import javax.net.ssl.HttpsURLConnection; /** * * @author marcelosiedler */ public class HttpExemplo { private final String USER_AGENT = "Mozilla/5.0"; public static void main(String[] args) throws Exception { HttpExemplo http = new HttpExemplo(); Gson gson = new Gson(); Pokemon pokemon = new Pokemon(); java.lang.reflect.Type pokemonType = new TypeToken<Pokemon>() { }.getType(); String chamadaWS = "http://192.168.25.6:8081/PokedexWS/webresources/pokews/poke/insert/trainer"; Trainer trainer = new Trainer(); trainer.setUsername("quadrado"); trainer.setEmail("quadrado"); trainer.setPassword("quadrado"); //System.out.println(gson.toJson(trainer)); String trainerToGson = gson.toJson(trainer); /*String trainerToGson = "{\"username\":"+ "\"" + trainer.getUsername()+ "\"" + "," + "\"email\":"+ "\"" + trainer.getEmail() + "\"" + "," + "\"password\":"+ "\"" + trainer.getPassword()+ "\"" + "}";*/ //System.out.println(trainerToGson); //String retorn = http.sendGet(chamadaWS, "DELETE"); //pokemon = gson.fromJson(json, pokemonType); //System.out.println(retorn); http.sendPost(chamadaWS,trainerToGson, "POST"); } // HTTP GET request private String sendGet(String url, String method) throws Exception { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // optional default is GET con.setRequestMethod(method); //add request header con.setRequestProperty("User-Agent", USER_AGENT); int responseCode = con.getResponseCode(); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result System.out.println(response.toString()); return response.toString(); } // HTTP POST request private void sendPost(String url, String parameters, String method) throws Exception { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod(method); con.setRequestProperty("Content-Type", "application/json"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = parameters; // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); System.out.println("\nSending 'POST' request to URL : " + url); System.out.println("Post parameters : " + urlParameters); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result System.out.println(response.toString()); } } android post volley singleton
    • Por Matheus Barbosa
      Estou com problemas ao compilar uma classe denominada Empregado que estende à classe Pessoa:
       
      package obj;
      public class Empregado extends Pessoa{
        private int codigoSetor;
        private double salBase, imposto;
        Empregado(String nome, String endereco, String telefone){
          super(nome, endereco, telefone);
        }
        public void setSetor(int codigoSetor){ this.codigoSetor = codigoSetor; }
        public void setSal(double salBase){ this.salBase = salBase; }
        public void setImposto(double imposto){ this.imposto = imposto; }
        public int getSetor(){ return codigoSetor; }
        public double getSal(){ return salBase; }
        public double getImposto(){ return imposto; }
        public double calculaSalario(){
          double novoSal;
          novoSal = salBase - (salBase*imposto/100);
          return novoSal;
        }
        @Override
        public void mostraDados(){
          System.out.println("O funcionario de nome: " + super.nome + ", endereço: " + super.endereco + " e telefone: " + super.telefone);
          System.out.println(", do setor: " + codigoSetor + " ira receber " + this.calculaSalario());
        }
      }
       
      package obj;
      public class Pessoa{
        private String nome, endereco, telefone;
        Pessoa(String nome, String endereco, String telefone){
          this.nome = nome;
          this.endereco = endereco;
          this.telefone = telefone;
        }
        public String getNome(){ return nome; }
        public String getEndereco(){ return endereco; }
        public String getTelefone(){ return telefone; }
        public void mostraDados(){
          System.out.println("Nome: " + nome + ", endereço: " + endereco + ", telefone: " + telefone);
        }
      }
       
      o codigo de erro do terminal linux é:
       
      Empregado.java:3: error: cannot find symbol
      public class Empregado extends Pessoa{
                                                                         ^
        symbol: class Pessoa
      Empregado.java:26: error: method does not override or implement a method from a supertype
        @Override
        ^
      Empregado.java:28: error: cannot find symbol
          System.out.println("O funcionario de nome: " + super.nome + ", endereço: " + super.endereco + " e telefone: " + super.telefone);
                                                                                                           ^
        symbol:   variable super
        location: class Empregado
      Empregado.java:28: error: cannot find symbol
          System.out.println("O funcionario de nome: " + super.nome + ", endereço: " + super.endereco + " e telefone: " + super.telefone);
                                                                                                          ^
        symbol:   variable super
        location: class Empregado
      Empregado.java:28: error: cannot find symbol
          System.out.println("O funcionario de nome: " + super.nome + ", endereço: " + super.endereco + " e telefone: " + super.telefone);
                                                                                                                                                                                                                                        ^
        symbol:   variable super
        location: class Empregado
      5 errors
       
      o meu programa esta em: /home/user/matheus/java/heranca/a/obj
       
       
       
       
       
    • Por paulaodaregulage
      Boa tarde Srs...
      Como poderia fazer para evitar que a ampliação da imagem ,através da ampliação do navegador ,estrague a posição das minhas informações(da planilha) que estavam propositalmente colocadas em cima do mapa?
       
      <table  id='estados'  background='mapa_brasil.png' border='1'> <tr> <td>dados 1a <td>  <td>dados 2a <td>  <td>dados 3a <td> </tr> <tr> <td>dados 1b<td>  <td>dados 2b <td>  <td>dados 3b <td> </tr> </table> <style>      #estados { width:85%; height:180%; position:absolute; max-width: 85%;      } </style>  
      obs.:desculpe por colocar o script fora do local correto....é pq estava dando erro para coloca-lo.
       
       
      obgd
       
       
    • Por Fernando Bastos
      # Function: Probability Matrix   def city_probability (attractiveness, thau, city = 0, alpha = 1, beta = 2, city_list = []):   probability = pd.DataFrame(0, index = attractiveness.index, columns = ['atraction','probability','cumulative_probability'])   for i in range(0, probability.shape[0]):   if (i+1 not in city_list):   probability.iloc[i, 0] = (thau.iloc[i, city]**alpha)*(attractiveness.iloc[i, city]**beta)   for i in range(0, probability.shape[0]):   if (i+1 not in city_list and probability['atraction'].sum() != 0):   probability.iloc[i, 1] = probability.iloc[i, 0]/probability['atraction'].sum()   if (i == 0):   probability.iloc[i, 2] = probability.iloc[i, 1]   else:   probability.iloc[i, 2] = probability.iloc[i, 1] + probability.iloc[i - 1, 2]       if (len(city_list) > 0):   for i in range(0, len(city_list)):   probability.iloc[city_list-1, 2] = 0.0       return probability
       
      Obrigado pessoal!
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.