Estás en: servicios web

servicios web

Para dar las gracias debes entrar o registrarte en el foro

Recién llegado
Recién llegado
Mensajes: 2 Agradecido: 0
30 Oct 2017, 21:19# 1

Buenas grupo, estoy siguiendo un curso de internet y tengo algún problemilla, el caso es que la variable no me la reconoce en postexecute, he intentado iniciaizarla en hilo principal y lo único que obtengo es el cierre la app. Agradecía mucho que alguien pueda echarle un vistazo.

El codigo:

package x.huertalia;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import android.util.Base64;
import java.lang.Object.*;
import android.view.View;
import android.widget.ImageView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.widget.Toast;
import static android.support.v7.appcompat.R.id.image;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

Button consultar;
Button consultarporid;
Button insertar;
Button actualizar;
Button borrar;
EditText idendificador;
EditText nombre;
EditText direccion;
EditText telefono;
EditText producto;
EditText precio;
TextView resultado;


// IP de mi Url
String IP = "http://yoelabreu8a.esy.es";
// Rutas de los Web Services
String GET = IP + "/obtener_alumnos.php";
String GET_BY_ID = IP + "/obtener_alumno_por_id.php";
String UPDATE = IP + "/actualizar_alumno.php";
String DELETE = IP + "/borrar_alumno.php";
String INSERT = IP + "/insertar_alumno.php";

ObtenerWebService hiloconexion;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);


// Enlaces con elementos visuales del XML

consultar = (Button)findViewById(R.id.consultar);
consultarporid = (Button)findViewById(R.id.consultarid);
insertar = (Button)findViewById(R.id.insertar);
actualizar = (Button)findViewById(R.id.actualizar);
borrar = (Button)findViewById(R.id.borrar);
idendificador = (EditText)findViewById(R.id.eid);
nombre = (EditText)findViewById(R.id.enombre);
direccion = (EditText)findViewById(R.id.edireccion);
telefono= (EditText)findViewById(R.id.etelefono);
producto = (EditText)findViewById(R.id.eproducto);
precio = (EditText)findViewById(R.id.eprecio);
resultado = (TextView)findViewById(R.id.resultado);

// Listener de los botones

consultar.setOnClickListener(this);
consultarporid.setOnClickListener(this);
insertar.setOnClickListener(this);
actualizar.setOnClickListener(this);
borrar.setOnClickListener(this);



FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "[email protected]", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, 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();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}

@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.consultar:

hiloconexion = new ObtenerWebService();
hiloconexion.execute(GET,"1"); // Parámetros que recibe doInBackground

break;
case R.id.consultarid:

hiloconexion = new ObtenerWebService();
String cadenallamada = GET_BY_ID + "?idalumno=" + idendificador.getText().toString();
hiloconexion.execute(cadenallamada,"2"); // Parámetros que recibe doInBackground


break;
case R.id.insertar:

hiloconexion = new ObtenerWebService();
hiloconexion.execute(INSERT,"3",nombre.getText().toString(),direccion.getText().toString()); // Parámetros que recibe doInBackground


break;
case R.id.actualizar:

hiloconexion = new ObtenerWebService();
hiloconexion.execute(UPDATE,"4",idendificador.getText().toString(),nombre.getText().toString(),direccion.getText().toString()); // Parámetros que recibe doInBackground


break;
case R.id.borrar:

hiloconexion = new ObtenerWebService();
hiloconexion.execute(DELETE,"5",idendificador.getText().toString()); // Parámetros que recibe doInBackground


break;
default:

break;
}
}

public class ObtenerWebService extends AsyncTask {

Bitmap bitmap;
String IMAGENES = IP + "/img/";
ImageView imageView;


@Override
protected String doInBackground(String... params) {

String cadena = params[0];
URL url = null; // Url de donde queremos obtener información
String devuelve ="";



if(params[1].equals("1")){ // Consulta de todos los alumnos

try {
url = new URL(cadena);
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //Abrir la conexión
connection.setRequestProperty("User-Agent", "Mozilla/5.0" +
" (Linux; Android 1.5; es-ES) Ejemplo HTTP");
//connection.setHeader("content-type", "application/json");

int respuesta = connection.getResponseCode();
StringBuilder result = new StringBuilder();

if (respuesta == HttpURLConnection.HTTP_OK){


InputStream in = new BufferedInputStream(connection.getInputStream()); // preparo la cadena de entrada

BufferedReader reader = new BufferedReader(new InputStreamReader(in)); // la introduzco en un BufferedReader

// El siguiente proceso lo hago porque el JSONOBject necesita un String y tengo
// que tranformar el BufferedReader a String. Esto lo hago a traves de un
// StringBuilder.

String line;
while ((line = reader.readLine()) != null) {
result.append(line); // Paso toda la entrada al StringBuilder
}

//Creamos un objeto JSONObject para poder acceder a los atributos (campos) del objeto.
JSONObject respuestaJSON = new JSONObject(result.toString()); //Creo un JSONObject a partir del StringBuilder pasado a cadena
//Accedemos al vector de resultados

String resultJSON = respuestaJSON.getString("estado"); // estado es el nombre del campo en el JSON



if (resultJSON.equals("1")){ // hay alumnos a mostrar
JSONArray alumnosJSON = respuestaJSON.getJSONArray("alumnos"); // estado es el nombre del campo en el JSON
for(int i=0;i devuelve = devuelve + alumnosJSON.getJSONObject(i).getString("idalumno") + " " +
alumnosJSON.getJSONObject(i).getString("nombre") + " " +
alumnosJSON.getJSONObject(i).getString("producto") + " " +
alumnosJSON.getJSONObject(i).getString("precio") + " " +
alumnosJSON.getJSONObject(i).getString("direccion") + "\n";

}

}
else if (resultJSON.equals("2")){
devuelve = "No hay agricultores";
}


}


} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}

return devuelve;


}
else if(params[1].equals("2")){ // consulta por id

try {
url = new URL(cadena);
HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //Abrir la conexión
connection.setRequestProperty("User-Agent", "Mozilla/5.0" +
" (Linux; Android 1.5; es-ES) Ejemplo HTTP");
//connection.setHeader("content-type", "application/json");

int respuesta = connection.getResponseCode();
StringBuilder result = new StringBuilder();

if (respuesta == HttpURLConnection.HTTP_OK){


InputStream in = new BufferedInputStream(connection.getInputStream()); // preparo la cadena de entrada

BufferedReader reader = new BufferedReader(new InputStreamReader(in)); // la introduzco en un BufferedReader

// El siguiente proceso lo hago porque el JSONOBject necesita un String y tengo
// que tranformar el BufferedReader a String. Esto lo hago a traves de un
// StringBuilder.

String line;
while ((line = reader.readLine()) != null) {
result.append(line); // Paso toda la entrada al StringBuilder
}

//Creamos un objeto JSONObject para poder acceder a los atributos (campos) del objeto.
JSONObject respuestaJSON = new JSONObject(result.toString()); //Creo un JSONObject a partir del StringBuilder pasado a cadena
//Accedemos al vector de resultados

String resultJSON = respuestaJSON.getString("estado"); // estado es el nombre del campo en el JSON

if (resultJSON.equals("1")){ // hay un alumno que mostrar
devuelve = devuelve + respuestaJSON.getJSONObject("alumno").getString("idAlumno") + " " +
respuestaJSON.getJSONObject("alumno").getString("nombre") + " " +
// respuestaJSON.getJSONObject("alumno").getString("producto")+" " +
// respuestaJSON.getJSONObject("alumno").getString("precio")+" " +
respuestaJSON.getJSONObject("alumno").getString("direccion");




if(respuestaJSON.getJSONObject("alumno").getString("rutaimagen").equals("noimagen")) {
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon_fallo);
}

else {

URL urlimagen = new URL(IMAGENES + respuestaJSON.getJSONObject("alumno").getString("rutaimagen"));
HttpURLConnection conimagen = (HttpURLConnection) urlimagen.openConnection();
conimagen.connect();
bitmap = BitmapFactory.decodeStream(conimagen.getInputStream());


}


}
else if (resultJSON.equals("2")){
devuelve = "No hay agricultores";
}


}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}

return devuelve;


}
else if(params[1].equals("3")){ // insert

try {
HttpURLConnection urlConn;

DataOutputStream printout;
DataInputStream input;
url = new URL(cadena);
urlConn = (HttpURLConnection) url.openConnection();
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.setRequestProperty("Accept", "application/json");
urlConn.connect();
//Creo el Objeto JSON
JSONObject jsonParam = new JSONObject();
jsonParam.put("nombre", params[2]);
jsonParam.put("direccion", params[3]);
// Envio los parámetros post.
OutputStream os = urlConn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(jsonParam.toString());
writer.flush();
writer.close();

int respuesta = urlConn.getResponseCode();


StringBuilder result = new StringBuilder();

if (respuesta == HttpURLConnection.HTTP_OK) {

String line;
BufferedReader br=new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
while ((line=br.readLine()) != null) {
result.append(line);
//response+=line;
}

//Creamos un objeto JSONObject para poder acceder a los atributos (campos) del objeto.
JSONObject respuestaJSON = new JSONObject(result.toString()); //Creo un JSONObject a partir del StringBuilder pasado a cadena
//Accedemos al vector de resultados

String resultJSON = respuestaJSON.getString("estado"); // estado es el nombre del campo en el JSON

if (resultJSON.equals("1")) { // hay un alumno que mostrar
devuelve = "Agricultor insertado correctamente";

} else if (resultJSON.equals("2")) {
devuelve = "El agricultor no pudo insertarse";
}

}

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}

return devuelve;


}
else if(params[1].equals("4")){ // update

try {
HttpURLConnection urlConn;

DataOutputStream printout;
DataInputStream input;
url = new URL(cadena);
urlConn = (HttpURLConnection) url.openConnection();
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.setRequestProperty("Accept", "application/json");
urlConn.connect();
//Creo el Objeto JSON
JSONObject jsonParam = new JSONObject();
jsonParam.put("idalumno",params[2]);
jsonParam.put("nombre", params[3]);
jsonParam.put("direccion", params[4]);
// Envio los parámetros post.
OutputStream os = urlConn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(jsonParam.toString());
writer.flush();
writer.close();

int respuesta = urlConn.getResponseCode();


StringBuilder result = new StringBuilder();

if (respuesta == HttpURLConnection.HTTP_OK) {

String line;
BufferedReader br=new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
while ((line=br.readLine()) != null) {
result.append(line);
//response+=line;
}

//Creamos un objeto JSONObject para poder acceder a los atributos (campos) del objeto.
JSONObject respuestaJSON = new JSONObject(result.toString()); //Creo un JSONObject a partir del StringBuilder pasado a cadena
//Accedemos al vector de resultados

String resultJSON = respuestaJSON.getString("estado"); // estado es el nombre del campo en el JSON

if (resultJSON.equals("1")) { // hay un alumno que mostrar
devuelve = "Agricultor actualizado correctamente";

} else if (resultJSON.equals("2")) {
devuelve = "El agricultor no pudo actualizarse";
}

}

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}

return devuelve;

}
else if(params[1].equals("5")) { // delete

try {
HttpURLConnection urlConn;

DataOutputStream printout;
DataInputStream input;
url = new URL(cadena);
urlConn = (HttpURLConnection) url.openConnection();
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.setRequestProperty("Accept", "application/json");
urlConn.connect();
//Creo el Objeto JSON
JSONObject jsonParam = new JSONObject();
jsonParam.put("idalumno", params[2]);
// Envio los parámetros post.
OutputStream os = urlConn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(jsonParam.toString());
writer.flush();
writer.close();

int respuesta = urlConn.getResponseCode();


StringBuilder result = new StringBuilder();

if (respuesta == HttpURLConnection.HTTP_OK) {

String line;
BufferedReader br=new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
while ((line=br.readLine()) != null) {
result.append(line);
//response+=line;
}

//Creamos un objeto JSONObject para poder acceder a los atributos (campos) del objeto.
JSONObject respuestaJSON = new JSONObject(result.toString()); //Creo un JSONObject a partir del StringBuilder pasado a cadena
//Accedemos al vector de resultados

String resultJSON = respuestaJSON.getString("estado"); // estado es el nombre del campo en el JSON

if (resultJSON.equals("1")) { // hay un alumno que mostrar
devuelve = "Agricultor borrado correctamente";

} else if (resultJSON.equals("2")) {
devuelve = "No hay agricultores";
}

}

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}

return devuelve;

}
return null;
}

@Override
protected void onCancelled(String s) {
super.onCancelled(s);
}

@Override
protected void onPostExecute(String s) {

resultado.setText(s);


imageView.setImageBitmap(bitmap);

//super.onPostExecute(s);
}

@Override
protected void onPreExecute() {
super.onPreExecute();
}

@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}

}

Gracias  
Etiquetado en:
Recién llegado
Recién llegado
Mensajes: 2 Agradecido: 0
30 Oct 2017, 21:23# 2

Por cierto lo que no me reconoce es imageView.setImageBitmap(bitmap);

Gracias  