I need some help, I am developing an app with php and android. I'm using the recycler view, but I'm having problems because my list has 3 items and is showing only one, could you help me? I will add my adapter and my main.
AdapterLocalPersonalizado
public class AdapterLocalPersonalizado extends RecyclerView.Adapter<AdapterLocalPersonalizado.MeuViewHolder> {
Context ctx;
List<Local> listaLocal;
connection con = new connection();
public AdapterLocalPersonalizado(List<Local> locais,Context ctx1) {
this.ctx = ctx1;
this.listaLocal = locais;
}
public class MeuViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView nome,categoria,endereco,valor;
#SuppressLint("WrongViewCast")
public MeuViewHolder(#NonNull View view) {
super(view);
nome = (TextView) view.findViewById(R.id.namec);
categoria = (TextView) view.findViewById(R.id.categoria);
valor = (TextView) view.findViewById(R.id.valor);
endereco = (TextView) view.findViewById(R.id.ende);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
Local objSelecionado = listaLocal.get(position);
if(position != RecyclerView.NO_POSITION){
Intent intent = new Intent(ctx.getApplicationContext(), tela_lista_local.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle bundle = new Bundle();
bundle.putInt("ID",objSelecionado.getId());
ctx.startActivity(intent);
}
}
}
#NonNull
#Override
public MeuViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
Local local = listaLocal.get(i);
Context context = viewGroup.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View linhaView = inflater.inflate(R.layout.activity_tela_lista_local_personalizada, viewGroup, false);
MeuViewHolder viewHolder = new MeuViewHolder(linhaView);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull AdapterLocalPersonalizado.MeuViewHolder meuViewHolder, int i) {
Local local = listaLocal.get(i);
TextView nome = meuViewHolder.nome;
nome.setText(local.getNome());
}
#Override
public int getItemCount() {
return listaLocal.size();
}
}
tela_lista_local (main)
public class tela_lista_local extends AppCompatActivity {
AdapterLocalPersonalizado adapterLocalPersonalizado;
List<Local> localList;
Local local;
String endereco,categoria,token;
connection con = new connection();
ListarLocalAsyncTask listarLocaisAsyncTask;
RecyclerView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tela_lista_local);
token = "tcc";
Intent it = getIntent();
categoria = it.getStringExtra("categoria");
endereco = it.getStringExtra("endereco");
listView = findViewById(R.id.recyclerViewLocal);
listarLocaisAsyncTask = new ListarLocalAsyncTask();
listarLocaisAsyncTask.execute();
}
public class ListarLocalAsyncTask extends AsyncTask<String, String, String> {
String api_token, query;
HttpURLConnection conn;
URL url = null;
Uri.Builder builder;
final String URL_WEB_SERVICES = "http://192.168.0.110/Controller/APIListarLocal.php";
final int READ_TIMEOUT = 10000; // MILISSEGUNDOS
final int CONNECTION_TIMEOUT = 30000;
int response_code;
public ListarLocalAsyncTask( ){
this.builder = new Uri.Builder();
builder.appendQueryParameter("api_categoria", categoria);
}
#Override
protected void onPreExecute() {
Log.i("APIListar", "onPreExecute()");
}
#Override
protected String doInBackground(String... strings) {
Log.i("APIListar", "doInBackground()");
// Gerar o conteúdo para a URL
try {
url = new URL(URL_WEB_SERVICES);
} catch (MalformedURLException e) {
Log.i("APIListar", "MalformedURLException --> " + e.getMessage());
} catch (Exception e) {
Log.i("APIListar", "doInBackground() --> " + e.getMessage());
}
// Gerar uma requisição HTTP - POST - Result será um ArrayJson
// conn
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setRequestProperty("charset", "utf-8");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
} catch (Exception e) {
Log.i("APIListar", "HttpURLConnection --> " + e.getMessage());
}
// Adicionar o TOKEN e/ou outros parâmetros como por exemplo
// um objeto a ser incluido, deletado ou alterado.
// CRUD completo
try {
query = builder.build().getEncodedQuery();
OutputStream stream = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(stream, "utf-8"));
writer.write(query);
writer.flush();
writer.close();
stream.close();
conn.connect();
} catch (Exception e) {
Log.i("APIListar", "BufferedWriter --> " + e.getMessage());
}
// receber o response - arrayJson
// http - código do response | 200 | 404 | 503
try {
response_code = conn.getResponseCode();
if (response_code == HttpURLConnection.HTTP_OK) {
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(input)
);
StringBuilder result = new StringBuilder();
String linha = null;
while ((linha = reader.readLine()) != null) {
result.append(linha);
}
return result.toString();
} else {
return "HTTP ERRO: " + response_code;
}
} catch (Exception e) {
Log.i("APIListar", "StringBuilder --> " + e.getMessage());
return "Exception Erro: " + e.getMessage();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
Log.i("APIListar", "onPostExecute()--> Result: " + result);
try {
Local local;
JSONArray jsonArray = new JSONArray(result);
localList = new ArrayList<>();
if (jsonArray.length() != 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
local = new Local(jsonObject.getInt("id"),
jsonObject.getString("nome"),
jsonObject.getString("endereco"),
jsonObject.getString("categoria"),
jsonObject.getString("valor"));
localList.add(local);
Log.i("APIListar", "Estado: -> " + local.getId() + " - " +local.getNome());
}
Toast.makeText(tela_lista_local.this, localList.size() + " local Listados no LogCat", Toast.LENGTH_LONG)
.show();
initial();
}
} catch (Exception e) {
Log.i("APIListar", "onPostExecute()--> " + e.getMessage());
}
}
public void initial(){
adapterLocalPersonalizado = new AdapterLocalPersonalizado(localList, getApplicationContext());
listView.setAdapter(adapterLocalPersonalizado);
listView.setLayoutManager(new LinearLayoutManager(tela_lista_local.this));
}
}
}
It just returns one item but my bank has 3. There are no problems with my API because in debug mode I can see the three items, the problem is when interacting with the list.
Thanks
I guess each item of your recycle view is taking the entire screen and you are only able to see only one item. As #Mike M suggested you can try to scroll and see other item are showing up or not.
If so then make sure your recycle view layout item are not android:layout_width="match_parent" android:layout_height="match_parent".
If you want specific reason, you must post activity_tela_lista_local_personalizada layout.
Happy Coding !
Related
I am trying get the dropdown list item from my database in my RecyclerView but whenever i try loading me recyclerView Activity the app crashes.
Code Form my RecyclerView Adapter :
public class Register_Adapter extends RecyclerView.Adapter<Register_Adapter.MyHolder> {
//Line number 40
private Context context;
List<dataRegComplaint> data = Collections.emptyList();
List<productlist> data1 = new ArrayList<>( );
Spinner product;
String total;
public static final int CONNECTION_TIMEOUT = 100000;
public static final int READ_TIMEOUT = 150000;
View v;
public Register_Adapter(complaintReg complaintReg,List<dataRegComplaint> data) {
this.context = complaintReg;
this.data = data;
}
#NonNull
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.container_register, viewGroup, false);
return new MyHolder( v );
//Line number 60
}
#Override
public void onBindViewHolder(#NonNull MyHolder myHolder, int i) {
final dataRegComplaint current=data.get(i);
myHolder.client.setText(current.getClientName());
myHolder.location.setText("Location: " + current.getAddress());
myHolder.category.setText("Reason: " + current.getCategory());
myHolder.locationid = current.getlocationid();
myHolder.complaint_register.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
total = current.getlocationid();
Log.e( TAG,"Location id :"+total );
context.startActivity( new Intent( context, Register_New_Complaint.class ) );
}
} );
}
#Override
public int getItemCount() {
return data.size();
}
public class MyHolder extends RecyclerView.ViewHolder{
TextView client,location,category;
Button complaint_register;
String locationid;
public MyHolder(#NonNull View itemView) {
super( itemView );
client = (TextView) itemView.findViewById( R.id.textclient );
location = (TextView) itemView.findViewById( R.id.textlocation );
product = (Spinner) itemView.findViewById( R.id.textproduct1 );
category = (TextView) itemView.findViewById( R.id.textcategory );
complaint_register = (Button) itemView.findViewById( R.id.button_register );
product.setOnItemSelectedListener( (AdapterView.OnItemSelectedListener) context );
}
//Line number 105
}
private class GetProduct extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
HttpURLConnection conn;
URL url = null;
try {
url = new URL( "http://100.98.115.205:8089/productlist.php" );
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout( READ_TIMEOUT );
conn.setConnectTimeout( CONNECTION_TIMEOUT );
conn.setRequestMethod( "POST" );
conn.setDoOutput( true );
OutputStream outputStream = conn.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter( new OutputStreamWriter( outputStream, "UTF-8" ) );
String post_data = URLEncoder.encode( "total", "UTF-8" ) + "=" + URLEncoder.encode(total, "UTF-8" );
Log.e( TAG, "POST DATAv :"+post_data );
bufferedWriter.write( post_data );
bufferedWriter.flush();
bufferedWriter.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader( new InputStreamReader( input ) );
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append( line );
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute( result );
Log.e( TAG, "RESULT :" +result );
try {
JSONArray jArray = new JSONArray( result );
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject( i );
productlist fishData = new productlist(
json_data.getString( "prod_name" ) );
data1.add( fishData );
Log.e( TAG, "DATA reesult :" +fishData );
}
populateSpinner();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void populateSpinner() {
List<String> lables = new ArrayList<String>();
for(int i = 0; i < data1.size(); i++){
lables.add( data1.get( i ).getSiteid());
Log.e( TAG, "Spinner :" +lables.add( data1.get( i ).getSiteid()) );
}
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>( context,android.R.layout.simple_spinner_dropdown_item, lables );
spinnerAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
product.setAdapter( spinnerAdapter );
}
}
LogCat :
java.lang.ClassCastException: nikhil.loginapp.com.complaintReg cannot be cast to android.widget.AdapterView$OnItemSelectedListener
at nikhil.loginapp.com.Register_Adapter$MyHolder.<init>(Register_Adapter.java:105)
at nikhil.loginapp.com.Register_Adapter.onCreateViewHolder(Register_Adapter.java:60)
at nikhil.loginapp.com.Register_Adapter.onCreateViewHolder(Register_Adapter.java:40)
I am getting my data in my PostExecute function but after that its showing error in Spinner and app crashes.
Some one help me out.
I'm using an adapter in a list, and the view of the buttons,
Some buttons are blocked, but if you scroll the drop-down list of this button is enabled with another wrong position that does not match, is there any way to solve this?
this is my Adapter
/**
* Created by Isai on 15/03/17.
*/
public class AdapterFood extends ArrayAdapter<Charola.Producto> {
ImageView imgFood;
private String nameService = "AgregarItemCharola";
private String usuarioId = "UsuarioId";
private String productoId = "ProductoId";
private String cantidad = "Cantidad";
private String especificaciones = "Especificaciones";
private String urlComplete = Constantes.URLMAIN + nameService + "?";
private Fragment fragment;
private List<Charola.Producto> productoList;
private int contador;
private String totalCharola;
public AdapterFood(Context context, List<Charola.Producto> productoList, Fragment fragment) {
super(context, 0, productoList);
this.fragment = fragment;
this.productoList = productoList;
}
#Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater)
getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View listViewInflate = convertView;
if (convertView == null) {
listViewInflate = inflater.inflate(R.layout.item_menu, viewGroup, false);
}
imgFood = (ImageView) listViewInflate.findViewById(R.id.imageFood);
TextView tituloFood = (TextView) listViewInflate.findViewById(R.id.tittleFood);
TextView descricionFood = (TextView) listViewInflate.findViewById(R.id.descriptionFood);
TextView precio = (TextView) listViewInflate.findViewById(R.id.priceFood);
final Button btnAnadir = (Button) listViewInflate.findViewById(R.id.buttonAnadir);
final Charola.Producto producto = getItem(position);
tituloFood.setText(producto.getNombre().toString());
descricionFood.setText(producto.getDescripcion());
precio.setText("$" + producto.getPrecio() + ".00");
if(producto.isExistencia()){
if (producto.getCantidad() != 0) {
btnAnadir.setText("+ Añadir (" + producto.getCantidad() + ")");
btnAnadir.setBackgroundResource(R.drawable.btns_dialogs);
} else {
btnAnadir.setText("+ Añadir");
btnAnadir.setBackgroundResource(R.drawable.btn_anadir);
}
btnAnadir.setTag(position);
btnAnadir.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("La etiqueta cambio del siguiente forma: "+ btnAnadir.getTag());
btnAnadir.setBackgroundResource(R.drawable.btns_dialogs);
new consumeServiceAgregarProductoACharola().execute(urlComplete + "#" + producto.getIdProducto());
System.out.println("+ Añadir("+(producto.getCantidad()+1)+")");
btnAnadir.setText("+ Añadir("+(producto.getCantidad()+1)+")");
producto.setCantidad((producto.getCantidad()+1));
//notifyDataSetChanged();
}
});
}else{
btnAnadir.setBackgroundResource(R.drawable.btn_agotado);
btnAnadir.setBackgroundResource(R.drawable.btn_agotado);
btnAnadir.setText("Agotado");
}
Glide.with(getContext()).
load(producto.getUrlFoto()).placeholder(R.drawable.place_holder)
.into(imgFood);
//Escalar Vistas
/* GuiTools guiTools = GuiTools.getCurrent();
guiTools.scale(tituloFood);
guiTools.scale(descricionFood);
guiTools.scale(precio);
guiTools.scale(btnAnadir);*/
notifyDataSetChanged();
return listViewInflate;
}
//recuperar id usuario
public int recuperarIdUsario() {
SharedPreferences sharedPreferences = getContext().getSharedPreferences("MIS_PREFRENCIAS", Context.MODE_PRIVATE);
int valor = sharedPreferences.getInt("id", 1);
return valor;
}
//Consume service AgregarProducto
class consumeServiceAgregarProductoACharola extends AsyncTask<String, Void, Void> {
private AlertDialogLoading loading;
#Override
protected Void doInBackground(String... params) {
String delimiter = "#";
String[] arrayLink = params[0].split("#");
URL url = null;
try {
url = new URL(arrayLink[0]);
Log.d("URL ---------->", url.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");// La conexión es por el metodo POST
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
urlConnection.connect();
JSONObject jsonParam = new JSONObject();
jsonParam.put("UsuarioId", recuperarIdUsario());
jsonParam.put("ProductoId", arrayLink[1]);
jsonParam.put("Cantidad", 1);
jsonParam.put("Especificaciones", "");
// Send POST output.
OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());
out.write(jsonParam.toString());
out.close();
StringBuilder sb = new StringBuilder();
int HttpResult = urlConnection.getResponseCode();
if (HttpResult == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream(), "utf-8"));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
JSONObject jsonObject = new JSONObject(sb.toString());
Log.d("RESPUESTA ----->",jsonObject.toString());
Log.d("TAMAÑO DEL CH------>", String.valueOf(jsonObject.getInt("TotalCharola")));
totalCharola = String.valueOf(jsonObject.getInt("TotalCharola"));
} else {
Log.e("NO SUCCESS", urlConnection.getResponseMessage());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = new AlertDialogLoading(fragment.getActivity());
loading.messageDialog("", "");
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
PrincipalViewController principalViewController = new PrincipalViewController();
principalViewController.ahBottomNavigation.setNotification(totalCharola,2);
loading.closeMessage();
}
}
}
trying to make a searchview works, with php and mysql.
user enters search query into search view/search bar to search for particular information, the query is sent to php file and result from php file is displayed on RecyclerView.
dont know whats wrong
MainActivity
public class MainActivity extends AppCompatActivity {
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVProd;
private AdapterProd mAdapter;
SearchView searchView = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.searchmain, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager) MainActivity.this.getSystemService(Context.SEARCH_SERVICE);
if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName()));
searchView.setIconified(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#Override
protected void onNewIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
if (searchView != null) {
searchView.clearFocus();
}
new AsyncFetch(query).execute();
}
}
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
HttpURLConnection conn;
URL url = null;
String searchQuery;
public AsyncFetch(String searchQuery){
this.searchQuery=searchQuery;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
url = new URL("http://192.168.0.2/prod-search.php");
} catch (MalformedURLException e) {
e.printStackTrace();
return e.toString();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
if (response_code == HttpURLConnection.HTTP_OK) {
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
return (result.toString());
} else {
return("Erro");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
pdLoading.dismiss();
List<DataProd> data=new ArrayList<>();
pdLoading.dismiss();
if(result.equals("no rows")) {
Toast.makeText(MainActivity.this, "Nenhum resultado encontrado", Toast.LENGTH_LONG).show();
}else{
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataProd prodData = new DataProd();
prodData.nomep = json_data.getString("nomeprod");
prodData.marcap = json_data.getString("marcaprod");
prodData.pesop = json_data.getInt("pesoprod");
prodData.valorp = json_data.getInt("valorprod");
prodData.pratp = json_data.getInt("pratprod");
data.add(prodData);
}
mRVProd = (RecyclerView) findViewById(R.id.listaprodpreco);
mAdapter = new AdapterProd(MainActivity.this, data);
mRVProd.setAdapter(mAdapter);
mRVProd.setLayoutManager(new LinearLayoutManager(MainActivity.this));
} catch (JSONException e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
}
Adapter
public class AdapterProd extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private LayoutInflater inflater;
List<DataProd> data= Collections.emptyList();
DataProd current;
int currentPos=0;
public AdapterProd(Context context, List<DataProd> data){
this.context=context;
inflater= LayoutInflater.from(context);
this.data=data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflater.inflate(R.layout.containerprod, parent, false);
MyHolder holder=new MyHolder(view);
return holder;
}
// Bind data
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
MyHolder myHolder= (MyHolder) holder;
DataProd current=data.get(position);
myHolder.textnomep.setText(current.nomep);
myHolder.textmarcap.setText("Marca: " + current.marcap);
myHolder.textpesop.setText("Peso: " + current.pesop);
myHolder.textvalorp.setText("Rs " + current.valorp + "\\Und");
myHolder.textvalorp.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));
myHolder.textpratp.setText("Prateleira: current.pratprod");
}
#Override
public int getItemCount() {
return data.size();
}
class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView textnomep;
TextView textmarcap;
TextView textpesop;
TextView textvalorp;
TextView textpratp;
public MyHolder(View itemView) {
super(itemView);
textnomep = (TextView) itemView.findViewById(R.id.textnomep);
textmarcap = (TextView) itemView.findViewById(R.id.textmarcap);
textpesop = (TextView) itemView.findViewById(R.id.textpesop);
textvalorp = (TextView) itemView.findViewById(R.id.textvalorp);
textpratp = (TextView) itemView.findViewById(R.id.textpratp);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(context, "Você clicou em um item", Toast.LENGTH_SHORT).show();
}
}
}
dont know what im doing wrong, keep getting this E/RecyclerView: No adapter attached; skipping layout, anyone can help?
Is there any chance that you are getting an exception while decoding the JSON and go directly to catch block, which skips the adapter initialization?
If you'd like to avoid that I'd suggest you to create an empty adapter set it to the recycler view when the UI initializes(in onCreate() for example), after that just have a method setData(List data) and use it to set the data after the async task finishes. In this case don't forget to call notifyDataSetChanged() when the data changes so that the recycler view is updated with the new data. This way you don't have to recreate the adapter each time you call the service.
PS: For your current code you will get that message each time the UI initializes as it doesn't have adapter attached. You should stop seeing this message once the async task finishes with no exceptions decoding the json.
JSONParser.class
package com.example.diptiagravat.myapplication;
public class JSONParser {
public String getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
}
} catch (MalformedURLException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
return null;
}
public String sendHTTPData(String urlpath, String id) {
HttpURLConnection connection = null;
try {
URL url=new URL(urlpath);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
OutputStreamWriter streamWriter = new OutputStreamWriter(connection.getOutputStream());
streamWriter.write(id);
streamWriter.flush();
StringBuilder stringBuilder = new StringBuilder();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK){
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(streamReader);
String response = null;
while ((response = bufferedReader.readLine()) != null) {
stringBuilder.append(response + "\n");
}
bufferedReader.close();
Log.d("test", stringBuilder.toString());
return stringBuilder.toString();
} else {
Log.e("test", connection.getResponseMessage());
return null;
}
} catch (Exception exception){
Log.e("test", exception.toString());
return null;
} finally {
if (connection != null){
connection.disconnect();
}
}
}
}
MainActivity.java
package com.example.diptiagravat.myapplication;
public class MainActivity extends AppCompatActivity {
private TextView txtid, txtcname;
Spinner spcnt, spstate;
public ArrayList<String> clist;
ArrayAdapter<String> cad;
public ArrayList<String> slist;
ArrayAdapter<String> sad;
public String strcnt;
private static String url = "http://urmiinfotech.com/demo/ifirst/app_api/get_country_list.php";
private static String stateUrl = "http://urmiinfotech.com/demo/ifirst/app_api/get_state_list.php";
private static final String TAG_USER = "country";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "country_name";
private ArrayList<Country> clistModels;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
CountryAsyncTask countryAsyncTask= new CountryAsyncTask();
countryAsyncTask.execute();
}
private void initViews() {
txtid = (TextView) findViewById(R.id.tvid);
txtcname = (TextView) findViewById(R.id.tvcname);
spcnt = (Spinner) findViewById(R.id.spcnt);
spstate = (Spinner) findViewById(R.id.spstate);
clist = new ArrayList<String>();
slist = new ArrayList<String>();
}
public class CountryAsyncTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = null;
try {
json = new JSONObject(jParser.getJSON(url, 5000));
} catch (JSONException e) {
e.printStackTrace();
}
return json.toString();
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.i("Result Ravi", result);
try {
JSONObject obj = new JSONObject(result);
JSONArray cntArray = obj.getJSONArray("country");
if (cntArray.length() > 0) {
for (int i = 0; i < cntArray.length(); i++) {
final JSONObject temp = cntArray.getJSONObject(i);
// txtid.setText(temp.getString("id"));
// txtcname.setText(temp.getString("country_name"));
Country country = new Gson().fromJson(temp.toString(), Country.class);
clist = new ArrayList<String>();
clistModels = new ArrayList<Country>();
clistModels.add(new Country(temp.optString("id"), temp.optString("country_name"), "", null));
clist.add(temp.getString("country_name"));
cad = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, clist);
spcnt.setAdapter(cad);
spcnt.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
strcnt = clistModels.get(position).getId();
//strcnt = parent.getItemAtPosition(position).toString();
Log.i("id", strcnt);
new StatesAsyncTask().execute();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// txtid.setText(temp.getString(country.getId()));
// txtcname.setText(temp.getString(country.getCountryName()));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class StatesAsyncTask extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = null;
try {
json = new JSONObject(jParser.sendHTTPData(stateUrl, strcnt));
} catch (JSONException e) {
e.printStackTrace();
}
return json.toString();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject obj = new JSONObject(s);
JSONArray stArray = obj.getJSONArray("statelist");
if (stArray.length() > 0) {
for (int i = 0; i < stArray.length(); i++) {
final JSONObject temp = stArray.getJSONObject(i);
// txtid.setText(temp.getString("id"));
// txtcname.setText(temp.getString("country_name"));
Statelist stlist = new Gson().fromJson(temp.toString(), Statelist.class);
slist = new ArrayList<String>();
// clistModels = new ArrayList<Country>();
//clistModels.add(new Country(temp.optString("id"), temp.optString("country_name"), "", null));
slist.add(temp.getString("state_name"));
sad = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, slist);
spstate.setAdapter(sad);
spstate.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// strcnt = clistModels.get(position).getId();
//strcnt = parent.getItemAtPosition(position).toString();
// Log.i("id", strcnt);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// txtid.setText(temp.getString(country.getId()));
// txtcname.setText(temp.getString(country.getCountryName()));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
My response is null?
HttpURLConnection is deprecated in Android Lollipop, so please try to use DefaultHttpClient instead. Also, check your logs, this is at your onPostExecute():
Log.i("Result Ravi", result);
For DefaultHttpClient check this post.
Another way is to try Retrofit
I have an app that connects to server sends sql request and get JSON answer as JsonArray.
Its Asynktask in seperate class (HTTPRequest.java is my AsyncTask class, Responce.java its my callback interface class) and it works correct.
when I use it in OrderActivity.java like below
#Override //my interface class function
public void onPostExecute(JSONArray Result) {
load(Result);
}
private void load(JSONArray json) {
for(int i=0;i<json.length();i++){
try {
JSONObject jo = json.getJSONObject(i);
Product p = new Product(
jo.getInt("ID"),
jo.getInt("parent"),
jo.getInt("category"),
jo.getString("Item"),
jo.getDouble("Price")
);
products.add(p);
} catch (JSONException e) {
e.printStackTrace();
}
}
it does work and fills product with data, but when I assign to my class variable JSONArray json
JSONArray json = new JSONArray;
.
.
.
#Override
public void onPostExecute(JSONArray Result) {
json = Result;
}
json is null
//HTTPRequest.java
public class HTTPRequest extends AsyncTask<String, Void, Integer> {
private Context context;
private Responce responce;
JSONArray json;
public HTTPRequest(Context context){
this.context = context;
responce = (Responce)context;
}
#Override
protected Integer doInBackground(String... params) {
OutputStream output;
InputStream inputStream = null;
HttpURLConnection connection = null;
String charset = "UTF-8";
Integer result = 0;
try {
URL uri = new URL(params[0]);
connection = (HttpURLConnection) uri.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "text/plain; charset=" + charset);
output = connection.getOutputStream();
output.write(params[1].getBytes(charset));
output.close();
int statusCode = connection.getResponseCode();
if (statusCode == 200) {
inputStream = new BufferedInputStream(connection.getInputStream());
json = new JSONArray(getJSON(inputStream));
result = 1;
}
} catch (Exception e) {
e.getLocalizedMessage();
}
return result;
}
#Override
protected void onPostExecute(Integer i) {
super.onPostExecute(i);
if(i == 1) {
responce.onPostExecute(json);
} else {
responce.onPostExecute(null);
}
}
private String getJSON(InputStream inputStream) throws IOException, JSONException {
StringBuffer stringBuffer = new StringBuffer();
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = null;
while((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line.toString());
}
result = stringBuffer.toString();
if(null!=inputStream){
inputStream.close();
}
return result;
}
}
//Responce.java
public interface Responce {
public void onPostExecute(JSONArray Result);
}
//OrderActivity.java
public class OrderActivity extends Activity implements Responce{
ArrayList<Product> products = new ArrayList<Product>();
ProductAdapter productAdapter;
OrderItemAdapter orderItemAdapter;
ListView orderlist;
JSONArray ja;
Button btnBack;
Button btnTakeOrder;
ListView picklist;
HTTPRequest httpRequest;
String url = "http://192.168.3.125:8888/data/";
String query = "select * from vwitems order by category desc";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
orderlist =(ListView)findViewById(R.id.orderlist);
orderItemAdapter = new OrderItemAdapter(OrderActivity.this);
btnBack = (Button)findViewById(R.id.btnBack);
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
productAdapter.filter(0);
}
});
btnTakeOrder = (Button)findViewById(R.id.btnTakeOrder);
btnTakeOrder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer oid = 0;
Order order = new Order(OrderActivity.this);
oid = order.NewOrder(1, 2, 3);
Toast.makeText(OrderActivity.this," " + order.getCount(), LENGTH_SHORT).show();
}
});
orderlist.setAdapter(orderItemAdapter);
picklist = (ListView) findViewById(R.id.picklist);
picklist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int pid = 0;
if (productAdapter.getItem(position).isCategory()) {
pid = productAdapter.getItem(position).getId();
productAdapter.filter(pid);
} else {
OrderItem oi = new OrderItem();
oi.setItemId(productAdapter.getItem(position).getId());
oi.setItem(productAdapter.getItem(position).getItem());
oi.setPrice(productAdapter.getItem(position).getPrice());
search(oi);
}
}
});
httpRequest = new HTTPRequest(this);
httpRequest.execute(url, query);
}
private boolean search(OrderItem oi){
int size = orderItemAdapter.getCount();
int i = 0;
if(size != 0)
for(OrderItem o : orderItemAdapter.getAll()){
if(o.getItemId() == oi.getItemId()){
orderItemAdapter.getItem(i).setQuantity(orderItemAdapter.getItem(i).getQuantity() + 1);
orderItemAdapter.notifyDataSetChanged();
return true;
}
i++;
}
orderItemAdapter.addItem(oi);
orderItemAdapter.notifyDataSetChanged();
return false;
}
private void load(JSONArray json) {
for(int i=0;i<json.length();i++){
try {
JSONObject jo = json.getJSONObject(i);
Product p = new Product(
jo.getInt("ID"),
jo.getInt("parent"),
jo.getInt("category"),
jo.getString("Item"),
jo.getDouble("Price")
);
products.add(p);
} catch (JSONException e) {
e.printStackTrace();
}
}
productAdapter = new ProductAdapter(OrderActivity.this, products);
picklist.setAdapter(productAdapter);
productAdapter.filter(0);
}
#Override
public void onPostExecute(JSONArray Result) {
load(Result);
}
/*
#Override
public void onPostExecute(JSONArray Result) {
json = Result;
}
**/
}
sorry i forgot include this one
//Order.java
public class Order implements Responce{
private Context context;
private JSONArray json = new JSONArray();
private HTTPRequest httpRequest;
private int OrderID;
private Date OrderDate;
private int OrderTable;
private int Waiter;
private byte OrderStatus;
private List<OrderItem> orderItems;
public Order(Context context){
this.context = context;
}
//some code here...
public Integer NewOrder(Integer guests, Integer waiter, Integer ordertable){
String query = "insert into orders(orderdate, guests, waiter, ordertable) VALUES(NOW()," + guests + ", " + waiter + ", " + ordertable + "); SELECT LAST_INSERT_ID() as ID;";
Integer result = 0;
Connect(query);
try {
JSONObject jo = json.getJSONObject(0);
result = jo.getInt("ID");
} catch (JSONException e) {
e.printStackTrace();
}
return result; //here i got 0 if i init result to 0, null or what ever i init my
}
#Override
public void onPostExecute(JSONArray Result) {
json = Result;
}
private void Connect (String query){
httpRequest = new HTTPRequest(context);
httpRequest.execute("http://192.168.3.125:8888/data/", query);
}
}