FACULDADE DE TECNOLOGIA SENAC PELOTAS Curso Superior

Propaganda
FACULDADE DE TECNOLOGIA SENAC PELOTAS
Curso Superior de Tecnologia em Análise e Desenvolvimento de Sistemas
Tópicos Avançados em ADS – Edécio Fernando Iepsen
================================== AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="br.com.edecio.listacarros">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".FiltroActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity" />
<activity android:name=".PropostaActivity"></activity>
</application>
</manifest>
-------------------------------- Carro.java
package br.com.edecio.listacarros;
import java.io.Serializable;
public class Carro implements Serializable {
public int id;
public String modelo;
public int ano;
public Double preco;
public String foto;
public Carro() {
}
public Carro(int id, String modelo, int ano, Double preco, String foto) {
this.id = id;
this.modelo = modelo;
this.ano = ano;
this.preco = preco;
this.foto = foto;
}
@Override
public String toString() {
return modelo;
}
}
-------------------------------- CarroHttp.java
package br.com.edecio.listacarros;
import
import
import
import
import
import
android.content.Context;
android.net.ConnectivityManager;
android.net.NetworkInfo;
org.json.JSONArray;
org.json.JSONException;
org.json.JSONObject;
import
import
import
import
import
import
import
java.io.ByteArrayOutputStream;
java.io.IOException;
java.io.InputStream;
java.net.HttpURLConnection;
java.net.URL;
java.util.ArrayList;
java.util.List;
public class CarroHttp {
public static final String CARROS_URL_JSON = "http://10.0.2.2/ws_revenda/index.php";
//public static final String CARROS_URL_JSON =
"http://192.168.200.3/edecio/topicos/lista.json";
private static HttpURLConnection connectar(String urlArquivo) throws IOException {
final int SEGUNDOS = 1000;
URL url = new URL(urlArquivo);
HttpURLConnection conexao = (HttpURLConnection)url.openConnection();
conexao.setReadTimeout(10 * SEGUNDOS);
conexao.setConnectTimeout(15 * SEGUNDOS);
conexao.setRequestMethod("GET");
conexao.setDoInput(true);
conexao.setDoOutput(false);
conexao.connect();
return conexao;
}
public static boolean temConexao(Context ctx) {
ConnectivityManager cm = (ConnectivityManager)
ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
return (info != null && info.isConnected());
}
public static List<Carro> carregarCarrosJson(String filtro) {
try {
HttpURLConnection conexao = connectar(CARROS_URL_JSON+"?"+filtro);
int resposta = conexao.getResponseCode();
if (resposta == HttpURLConnection.HTTP_OK) {
InputStream is = conexao.getInputStream();
JSONObject json = new JSONObject(bytesParaString(is));
return lerJsonCarros(json);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static List<Carro> lerJsonCarros(JSONObject json) throws JSONException {
List<Carro> listaDeCarros = new ArrayList<Carro>();
JSONArray jsonCarros = json.getJSONArray("carros");
for (int i = 0; i < jsonCarros.length(); i++) {
JSONObject jsonCarro = jsonCarros.getJSONObject(i);
Carro carro = new Carro(
jsonCarro.getInt("id"),
jsonCarro.getString("modelo"),
jsonCarro.getInt("ano"),
jsonCarro.getDouble("preco"),
jsonCarro.getString("foto")
);
listaDeCarros.add(carro);
}
return listaDeCarros;
}
private static String bytesParaString(InputStream is) throws IOException {
byte[] buffer = new byte[1024];
// O bufferzao vai armazenar todos os bytes lidos
ByteArrayOutputStream bufferzao = new ByteArrayOutputStream();
// precisamos saber quantos bytes foram lidos
int bytesLidos;
// Vamos lendo de 1KB por vez...
while ((bytesLidos = is.read(buffer)) != -1) {
// copiando a quantidade de bytes lidos do buffer para o bufferzão
bufferzao.write(buffer, 0, bytesLidos);
}
return new String(bufferzao.toByteArray(), "UTF-8");
}
}
------------------------------------- CarrosListAdapter.java
package br.com.edecio.listacarros;
import
import
import
import
import
import
import
import
import
android.content.Context;
android.view.LayoutInflater;
android.view.View;
android.view.ViewGroup;
android.widget.ArrayAdapter;
android.widget.ImageView;
android.widget.TextView;
com.squareup.picasso.Picasso;
java.util.List;
public class CarrosListAdapter extends ArrayAdapter<Carro>{
public static final String CARROS_URL_FOTO = "http://10.0.2.2/ws_revenda/";
//public static final String CARROS_URL_FOTO = "http://192.168.200.3/edecio/topicos/";
public CarrosListAdapter(Context context, List<Carro> objects) {
super(context, 0, objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Carro carro = getItem(position);
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.item_carro_list, null);
holder = new ViewHolder();
holder.imgFoto = (ImageView)convertView.findViewById(R.id.imgFoto);
holder.txtModelo = (TextView)convertView.findViewById(R.id.txtModelo);
holder.txtPreco = (TextView)convertView.findViewById(R.id.txtPreco);
holder.txtAno = (TextView)convertView.findViewById(R.id.txtAno);
holder.txtId = (TextView)convertView.findViewById(R.id.txtId);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
Picasso.with(getContext()).load(CARROS_URL_FOTO+carro.foto).into(holder.imgFoto);
holder.txtModelo.setText(carro.modelo);
// 0: não encontrado
if (carro.id > 0) {
holder.txtPreco.setText("R$: " + String.valueOf(carro.preco));
holder.txtAno.setText("Ano: " + String.valueOf(carro.ano));
holder.txtId.setText("
(Id:" + String.valueOf(carro.id) + ")");
}
return convertView;
}
static class ViewHolder {
ImageView imgFoto;
TextView txtModelo;
TextView txtPreco;
TextView txtAno;
TextView txtId;
}
}
------------------------------------- CarrosListFragment.java
package br.com.edecio.listacarros;
import
import
import
import
import
import
import
import
android.app.Fragment;
android.content.Intent;
android.os.AsyncTask;
android.os.Bundle;
android.view.LayoutInflater;
android.view.View;
android.view.ViewGroup;
android.widget.AdapterView;
import
import
import
import
import
android.widget.ArrayAdapter;
android.widget.ListView;
android.widget.ProgressBar;
android.widget.TextView;
android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import static android.widget.Toast.*;
public class CarrosListFragment extends Fragment implements AdapterView.OnItemClickListener {
CarrosTask mTask;
List<Carro> mCarros;
ListView mListView;
TextView mTextMensagem;
ProgressBar mProgressBar;
ArrayAdapter<Carro> mAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragment_carros_list, null);
mTextMensagem = (TextView)layout.findViewById(android.R.id.empty);
mProgressBar = (ProgressBar)layout.findViewById(R.id.progressBar);
mListView = (ListView)layout.findViewById(R.id.list);
mListView.setEmptyView(mTextMensagem);
return layout;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (mCarros == null) {
mCarros = new ArrayList<Carro>();
}
mAdapter = new CarrosListAdapter(getActivity(), mCarros);
//mAdapter = new ArrayAdapter<Carro>(getActivity(),
android.R.layout.simple_list_item_1, mCarros);
mListView.setAdapter(mAdapter);
if (mTask == null) {
if (CarroHttp.temConexao(getActivity())) {
iniciarDownload();
} else {
mTextMensagem.setText("Sem conexão");
}
} else if (mTask.getStatus() == AsyncTask.Status.RUNNING) {
exibirProgress(true);
}
// acrescenta chamada ao evento OnItemClick
mListView.setOnItemClickListener(this);
}
private void exibirProgress(boolean exibir) {
if (exibir) {
mTextMensagem.setText("Baixando informações dos carros...");
}
mTextMensagem.setVisibility(exibir ? View.VISIBLE : View.GONE);
mProgressBar.setVisibility(exibir ? View.VISIBLE : View.GONE);
}
public void iniciarDownload() {
if (mTask == null || mTask.getStatus() != AsyncTask.Status.RUNNING) {
// obtém a variável da Activity
String filtro = MainActivity.filtro;
mTask = new CarrosTask();
mTask.execute(filtro);
}
}
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Carro carro = (Carro) adapterView.getItemAtPosition(i);
// Toast.makeText(getActivity(), "Clicou em " + carro.modelo + " Ano: " + carro.ano,
LENGTH_LONG).show();
if (carro.id > 0) {
Intent it = new Intent(getActivity(), PropostaActivity.class);
it.putExtra("modelo", carro.modelo);
it.putExtra("ano", carro.ano);
it.putExtra("id", carro.id);
it.putExtra("preco", carro.preco);
it.putExtra("foto", carro.foto);
startActivity(it);
}
}
class CarrosTask extends AsyncTask<String, Void, List<Carro>>{
@Override
protected void onPreExecute() {
super.onPreExecute();
exibirProgress(true);
}
@Override
protected List<Carro> doInBackground(String... strings) {
return CarroHttp.carregarCarrosJson(strings[0]);
}
@Override
protected void onPostExecute(List<Carro> carros) {
super.onPostExecute(carros);
exibirProgress(false);
if (carros != null) {
mCarros.clear();
mCarros.addAll(carros);
mAdapter.notifyDataSetChanged();
} else {
mTextMensagem.setText("Falha ao obter os carros");
}
}
}
}
------------------------------------ FiltroActivity.java
package br.com.edecio.listacarros;
import
import
import
import
import
import
import
import
android.content.Intent;
android.support.v7.app.AppCompatActivity;
android.os.Bundle;
android.view.View;
android.widget.Button;
android.widget.EditText;
android.widget.TextView;
android.widget.Toast;
public class FiltroActivity extends AppCompatActivity implements View.OnClickListener {
private Button btnPesquisar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_filtro);
btnPesquisar = (Button) findViewById(R.id.btnPesquisar);
btnPesquisar.setOnClickListener(this);
}
@Override
public void onClick(View view) {
EditText edtFiltroModelo = (EditText) findViewById(R.id.edtFiltroModelo);
EditText edtMinimo = (EditText) findViewById(R.id.edtMinimo);
EditText edtMaximo = (EditText) findViewById(R.id.edtMaximo);
String modelo = edtFiltroModelo.getText().toString();
String minimo = edtMinimo.getText().toString();
String maximo = edtMaximo.getText().toString();
// verifica se foi preenchido as views de edição
if (modelo.matches("") && minimo.matches("") && maximo.matches("")) {
Toast.makeText(this, "Preecha, no mínimo, um dos campos",
Toast.LENGTH_LONG).show();
edtFiltroModelo.requestFocus();
return;
}
Intent it = new Intent(this, MainActivity.class);
it.putExtra("modelo", modelo);
it.putExtra("minimo", minimo);
it.putExtra("maximo", maximo);
startActivity(it);
}
}
---------------------------------------- MainActivity.java
package br.com.edecio.listacarros;
import
import
import
import
android.content.Intent;
android.support.v7.app.AppCompatActivity;
android.os.Bundle;
android.widget.Toast;
public class MainActivity extends AppCompatActivity {
protected static String filtro;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent
String
String
String
it = getIntent();
modelo = it.getStringExtra("modelo");
minimo = it.getStringExtra("minimo");
maximo = it.getStringExtra("maximo");
filtro = "modelo="+modelo+"&minimo="+minimo+"&maximo="+maximo;
setContentView(R.layout.activity_main);
}
}
-------------------------------------- PropostaActivity.java
package br.com.edecio.listacarros;
import
import
import
import
import
import
import
import
import
import
android.content.Intent;
android.os.AsyncTask;
android.support.v7.app.AppCompatActivity;
android.os.Bundle;
android.view.View;
android.widget.Button;
android.widget.EditText;
android.widget.ImageView;
android.widget.TextView;
android.widget.Toast;
import com.squareup.picasso.Picasso;
import org.json.JSONException;
import org.json.JSONObject;
import
import
import
import
import
import
import
java.io.BufferedReader;
java.io.DataOutputStream;
java.io.IOException;
java.io.InputStreamReader;
java.net.HttpURLConnection;
java.net.URL;
java.nio.charset.StandardCharsets;
public class PropostaActivity extends AppCompatActivity
implements View.OnClickListener {
public static final String CARROS_URL_FOTO = "http://10.0.2.2/ws_revenda/";
private
private
private
private
private
ImageView imgPropFoto;
TextView txtPropVeiculo;
EditText edtEmail;
EditText edtProposta;
Button btnEnviar;
private int idCarro;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_proposta);
txtPropVeiculo = (TextView) findViewById(R.id.txtPropVeiculo);
imgPropFoto = (ImageView) findViewById(R.id.imgPropFoto);
edtEmail = (EditText) findViewById(R.id.edtEmail);
edtProposta = (EditText) findViewById(R.id.edtProposta);
btnEnviar = (Button) findViewById(R.id.btnEnviar);
Intent it = getIntent();
String modelo = it.getStringExtra("modelo");
int ano = it.getIntExtra("ano", 0);
Double preco = it.getDoubleExtra("preco", 0);
String foto = it.getStringExtra("foto");
idCarro = it.getIntExtra("id", 0);
txtPropVeiculo.setText(modelo + " " + ano + " - R$: "+preco);
Picasso.with(getApplicationContext()).load(CARROS_URL_FOTO+foto).into(imgPropFoto);
// joga o foco no edtEmail
edtEmail.requestFocus();
btnEnviar.setOnClickListener(this);
}
@Override
public void onClick(View view) {
String email = edtEmail.getText().toString();
String proposta = edtProposta.getText().toString();
String idCarroProposta = String.valueOf(idCarro);
enviaDados task = new enviaDados();
task.execute("http://10.0.2.2/ws_revenda/cad_proposta.php", email, proposta,
idCarroProposta);
}
private class enviaDados extends AsyncTask<String, Void, JSONObject> {
@Override
protected JSONObject doInBackground(String... strings) {
String path = strings[0];
String email = strings[1];
String proposta = strings[2];
String idCarroProposta = strings[3];
// cria um objeto HttpURLConnection
HttpURLConnection conn = null;
try {
URL url = new URL(path);
// abre a conexão
conn = (HttpURLConnection) url.openConnection();
// define o método de envio dos dados
conn.setRequestMethod("POST");
// define os dados a serem enviados
String dados =
"idcarro="+idCarroProposta+"&email="+email+"&proposta="+proposta;
conn.setDoOutput(true);
// envia os dados
try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) {
out.write(dados.getBytes(StandardCharsets.UTF_8));
}
// define uma StringBuilder para obter o retorno (JSON)
StringBuilder resposta = new StringBuilder();
// cria um BufferReader para ler os dados de retorno do WebService
try (BufferedReader in = new BufferedReader(new
InputStreamReader(conn.getInputStream()))) {
String linha;
while ((linha = in.readLine()) != null) {
resposta.append(linha);
}
}
return new JSONObject(resposta.toString());
} catch (IOException | JSONException e) {
e.printStackTrace();
return null;
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
@Override
protected void onPostExecute(JSONObject jsonObject) {
try {
int cod = jsonObject.getInt("wsId");
String mensa = jsonObject.getString("wsMsg");
Toast.makeText(PropostaActivity.this, "Cód: " + cod + " - Mensagem: " + mensa,
Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
================================= activity_filtro.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="br.com.edecio.listacarros.FiltroActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Preencha, no mínimo, um dos campos abaixo"/>
<EditText
android:id="@+id/edtFiltroModelo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Modelo do Veículo"
android:layout_marginTop="20dp"/>
<EditText
android:id="@+id/edtMinimo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="R$ Mínimo" />
<EditText
android:id="@+id/edtMaximo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="R$ Máximo" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnPesquisar"
android:text="Pesquisar"
android:layout_marginTop="20dp"/>
</LinearLayout>
================================== activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="br.com.edecio.listacarros.CarrosListFragment"
android:id="@+id/listFragment"/>
</FrameLayout>
================================== activity_proposta.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="br.com.edecio.listacarros.PropostaActivity">
<ImageView
android:id="@+id/imgPropFoto"
android:layout_width="match_parent"
android:layout_height="150dp" />
<TextView
android:id="@+id/txtPropVeiculo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAlignment="center"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Quer fazer uma proposta para este veículo?"
android:layout_marginTop="12dp"/>
<EditText
android:id="@+id/edtEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:hint="Seu E-mail"
android:inputType="textEmailAddress"
android:layout_marginTop="10dp"/>
<EditText
android:id="@+id/edtProposta"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:inputType="textMultiLine"
android:lines="2"
android:gravity="top|left"
android:scrollbars="vertical"
android:hint="Proposta (aceitamos troca por veículo de menor valor)"/>
<Button
android:id="@+id/btnEnviar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Enviar Proposta"
android:layout_marginTop="12dp"/>
</LinearLayout>
==================================== fragment_carros_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/progressBar"
android:layout_centerInParent="true"
android:visibility="gone"/>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/list" />
<TextView
android:id="@android:id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="@+id/progressBar"/>
</RelativeLayout>
====================================== item_carro_list.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="wrap_content"
android:layout_gravity="center_vertical"
android:padding="6dp">
<ImageView
android:layout_width="160dp"
android:layout_height="100dp"
android:id="@+id/imgFoto"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@null"
android:id="@+id/txtModelo"
android:layout_alignTop="@id/imgFoto"
android:layout_toRightOf="@id/imgFoto"
android:layout_toEndOf="@id/imgFoto" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@null"
android:id="@+id/txtPreco"
android:layout_below="@id/txtModelo"
android:layout_toRightOf="@id/imgFoto"
android:layout_toEndOf="@id/imgFoto" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@null"
android:id="@+id/txtAno"
android:layout_below="@id/txtPreco"
android:layout_toRightOf="@id/imgFoto"
android:layout_toEndOf="@id/imgFoto" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="@null"
android:id="@+id/txtId"
android:layout_alignTop="@id/txtAno"
android:layout_toRightOf="@id/imgFoto"
android:layout_toEndOf="@id/txtAno" />
</RelativeLayout>
<?php
header("Content-type: application/json; charset=utf-8");
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ws_revenda";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$modelo = htmlspecialchars($_GET["modelo"]);
$minimo = htmlspecialchars($_GET["minimo"]);
$maximo = htmlspecialchars($_GET["maximo"]);
// vai "acumular" os filtros indicados
$filtro = "";
if (!empty($modelo)) {
$filtro = "modelo like '%$modelo%'";
}
if (!empty($minimo)) {
if (empty($filtro)) {
$filtro = "preco >= $minimo";
} else {
$filtro .= " and preco >= $minimo";
}
}
if (!empty($maximo)) {
if (empty($filtro)) {
$filtro = "preco <= $maximo";
} else {
$filtro .= " and preco <= $maximo";
}
}
$sql = "SELECT * FROM carros where $filtro order by preco";
$result = $conn->query($sql);
$carros = array();
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
$linha = array("id" => $row["id"], "modelo" => utf8_encode($row["modelo"]), "ano" =>
$row["ano"], "preco" => $row["preco"], "foto" => $row["foto"]);
$carros[] = $linha;
}
} else {
$linha = array("id" => 0, "modelo" => "Não há veículos", "ano" => "0", "preco" => "0",
"foto" => "fotos/zero.jpg");
$carros[] = $linha;
}
$lista = array("carros" => $carros);
$conn->close();
echo json_encode($lista, JSON_PRETTY_PRINT);
<?php
header("Content-type: application/json; charset=utf-8");
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ws_revenda";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
$dataRet = array("wsId"=>0,
"wsMsg"=>utf8_encode("Erro de Acesso ao Banco de Dados"));
echo json_encode($dataRet);
return;
}
$idcarro = htmlspecialchars($_POST["idcarro"]);
$email = htmlspecialchars($_POST["email"]);
$proposta = htmlspecialchars($_POST["proposta"]);
$sql = "INSERT INTO propostas (carros_id, email, proposta) VALUES ($idcarro, '$email',
'$proposta')";
// se a execução do comando retornar true
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
$dataRet = array("wsId"=>1,
"wsMsg"=>utf8_encode("Ok! Proposta Cadastrada. Aguarde Contato"));
} else {
$dataRet = array("wsId"=>0,
"wsMsg"=>utf8_encode("Erro no Envio da Proposta " . $conn->error));
}
echo json_encode($dataRet);
$conn->close();
Download