Populate spinner using mysql in android - android

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.

Related

recycler view showing only one item instead of three

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 !

Pull down to refresh in RecyclerView [duplicate]

This question already has answers here:
Pull to refresh recyclerview android
(7 answers)
Closed 4 years ago.
Bear my English
Whenever any data is added in my database then on refresh the data should be reflected.
And one more thing can you help me Regarding how do I create notification if any new data is Added
I am using:
1) Xampp for Apache
2) Microsoft SQL Server
This is my RecyclerActivtiy
Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_engineer_recycler );
Bundle bundle = getIntent().getExtras();
service_id = bundle.getString( "empid" );
type_id = bundle.getString( "type" );
if(type_id.equals( "pending" )){
this.setTitle( "Pending Complaint " );
}else if(type_id.equals( "history" )){
this.setTitle( "Complaint History" );
}
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat( "dd/MM/yyyy" );
String time = format.format( calendar.getTime() );
Log.e( TAG, "Time" +time );
new AsyncLogin().execute(service_id,type_id, time);
}
private class AsyncLogin extends AsyncTask<String, String, String> {
ProgressDialog pdloding = new ProgressDialog(EngineerRecycler.this);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute(){
super.onPreExecute();
pdloding.setMessage( "\tLoading.." );
pdloding.setCancelable( false );
pdloding.show();
}
#Override
protected String doInBackground(String... strings) {
try {
serviceid = (String) strings[0];
typeid = (String) strings[1];
time1 = (String) strings[2];
if(typeid.equals( "pending" )){
url = new URL("http://localhost/players.php");
}else if(typeid.equals( "history" )){
url = new URL("http:/localhost/StudentDetails.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.setDoOutput(true);
OutputStream outputStream = conn.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter( new OutputStreamWriter( outputStream, "UTF-8" ) );
String post_data = URLEncoder.encode( "serviceid","UTF-8" ) + "=" + URLEncoder.encode( serviceid, "UTF-8" ) + "&"
+URLEncoder.encode( "time1","UTF-8" ) + "=" + URLEncoder.encode( time1, "UTF-8" );
bufferedWriter.write( post_data );
bufferedWriter.flush();
bufferedWriter.close();
Log.e( TAG, "POST DATA "+post_data );
} 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) {
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){
Log.e( TAG,"result"+result );
pdloding.dismiss();
List<DataComplaint> data = new ArrayList<>( );
pdloding.dismiss();
if(result.equals( "No complaint assgin null" )){
Toast.makeText( EngineerRecycler.this, "No Complaint Assign", Toast.LENGTH_SHORT ).show();
}else{
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);
DataComplaint fishData = new DataComplaint(
json_data.getString("comp_desc"),
json_data.getString("comp_reason"),
json_data.getString("ClientName"),
json_data.getString( "SiteName" ),
json_data.getString( "comp_ticketid" ));
data.add(fishData);
}
cAdapter.notifyDataSetChanged();
// Setup and Handover data to recyclerview
complaints = (RecyclerView)findViewById(R.id.complaintList);
cAdapter = new complaintAdapter(EngineerRecycler.this, data,service_id, type_id);
complaints.setAdapter(cAdapter);
complaints.setLayoutManager(new LinearLayoutManager(EngineerRecycler.this));
} catch (JSONException e) {
}
}
}
}
This the code for my Adapter
Code:
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.container_complaint, viewGroup, false);
return new MyHolder( v );
}
#Override
public void onBindViewHolder(#NonNull final MyHolder myHolder, final int i) {
final DataComplaint current=data.get(i);
myHolder.textcomplaint.setText(current.complaint);
myHolder.textaddress.setText("Reason: " + current.getAddress());
myHolder.textType.setText("Client : " + current.getComplaint_type());
myHolder.textplace.setText("Location: " + current.getLocation());
myHolder.textticket.setText( current.getTicket());
myHolder.linearLayout.setVisibility( View.GONE );
}
#Override
public int getItemCount() {
return data.size();
}
public class MyHolder extends RecyclerView.ViewHolder {
TextView textcomplaint;
TextView textaddress;
TextView textType,textplace, textticket, textreso;
Button btn, btn1, btn2;
int value1;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
LinearLayout linearLayout;
RelativeLayout relativeView;
public MyHolder(#NonNull View itemView) {
super( itemView );
textcomplaint = (TextView) itemView.findViewById( R.id.textcomplaint );
textaddress = (TextView) itemView.findViewById( R.id.textaddress );
textType = (TextView) itemView.findViewById( R.id.textType );
textticket = (TextView) itemView.findViewById( R.id.ticketid );
textplace = (TextView) itemView.findViewById( R.id.textplace );
btn = (Button) itemView.findViewById( R.id.enter );
btn1 = (Button) itemView.findViewById( R.id.repositry );
btn2 = (Button) itemView.findViewById( R.id.exit );
linearLayout = (LinearLayout) itemView.findViewById( R.id.linear_layout );
relativeView = (RelativeLayout) itemView.findViewById( R.id.view );
}
Here the problem is how implement pull down to refresh function in my recyclerview.
And Where to write function for it whether in RecyclerActivity or in Adapter.
Can anyone help me out regarding this problem.
You can wrap you RecyclerView with the SwipeRefreshLayout for making a pull to refresh.
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/refreshView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</android.support.v4.widget.SwipeRefreshLayout>
And you should listen to refresh events for the SwipeRefreshLayout:
refreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
// Load data to your RecyclerView
refreshData();
}
});

ListView Scrolling Reset

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();
}
}
}

Populate data into listview using json parsom with restful api

I have to run json format which is shown in below
and have to parse this data into listview
and for this i tried following code
MainActivity
swipeRefreshLayout.setOnRefreshListener(this);
// swipeRefreshLayout.setRefreshing(true);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
SyncMethod("http://52.26.35.210/api/web/v1/api-beautician/country-state-city");
}
}
);
notification_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String postloadid = actorsList.get(position).gettitle();
String source_addoc=actorsList.get(position).gettitle();
Constants.vCountry=actorsList.get(position).gettitle();
Toast.makeText(getApplicationContext(),"Selecting "+ Constants.vCountry+" State ", Toast.LENGTH_LONG).show();
finish();
}
});
}
public void init()
{
norecord=(LinearLayout)findViewById(R.id.norecord);
notification_listview=(ListView)findViewById(R.id.listView_notification);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
}
#Override
public void onRefresh()
{
swipeRefreshLayout.setRefreshing(false);
SyncMethod("http://52.26.35.210/api/web/v1/api-beautician/country-state-city");
}
private static String pad(int c)
{
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
#Override
public void onResume()
{
super.onResume();
swipeRefreshLayout.setRefreshing(false);
SyncMethod("http://52.26.35.210/api/web/v1/api-beautician/country-state-city");
}
public void SyncMethod(final String GetUrl)
{
Log.i("Url.............", GetUrl);
final Thread background = new Thread(new Runnable() {
// After call for background.start this run method call
public void run() {
try {
String url = GetUrl;
String SetServerString = "";
// document all_stuff = null;
SetServerString = fetchResult(url);
threadMsg(SetServerString);
} catch (Throwable t) {
Log.e("Animation", "Thread exception " + t);
}
}
private void threadMsg(String msg) {
if (!msg.equals(null) && !msg.equals("")) {
Message msgObj = handler11.obtainMessage();
Bundle b = new Bundle();
b.putString("message", msg);
msgObj.setData(b);
handler11.sendMessage(msgObj);
}
}
// Define the Handler that receives messages from the thread and update the progress
private final Handler handler11 = new Handler() {
public void handleMessage(Message msg) {
try {
String aResponse = msg.getData().getString("message");
Log.e("Exam", "screen>>" + aResponse);
swipeRefreshLayout.setRefreshing(false);
JSONObject jobj = new JSONObject(aResponse);
Log.e("Home Get draft--", jobj.toString());
String status = jobj.getString("status");
Log.e("Myorder Homestatusdraft",status);
Log.e("--------------------", "----------------------------------");
if (status.equalsIgnoreCase("true"))
{
actorsList = new ArrayList<Doctortype_method>();
JSONArray array = new JSONArray();
array = jobj.getJSONArray("response");
if(actorsList.size()>0){
actorsList.clear();
}
for(int i=0;i<array.length();i++)
{
JSONObject jsonChildNode = array.getJSONObject(i);
actorsList.add(new Doctortype_method(jsonChildNode.optString("State id"),jsonChildNode.optString("State name")));
}
if (getApplicationContext() != null)
{
if (adapter == null)
{
adapter = new Doctortype_Adapter(getApplicationContext(),actorsList);
notification_listview.setAdapter(adapter);
} else {
adapter.notifyDataSetChanged();
}
}
if(actorsList.size()==0)
{
norecord.setVisibility(View.VISIBLE);
}
}
else
{
swipeRefreshLayout.setRefreshing(false);
norecord.setVisibility(View.VISIBLE);
// UF.msg(message + "");
}
} catch (Exception e) {
}
}
};
});
// Start Thread
background.start();
}
public String fetchResult(String urlString) throws JSONException {
StringBuilder builder;
BufferedReader reader;
URLConnection connection = null;
URL url = null;
String line;
builder = new StringBuilder();
reader = null;
try {
url = new URL(urlString);
connection = url.openConnection();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
//Log.d("DATA", builder.toString());
} catch (Exception e) {
}
//JSONArray arr=new JSONArray(builder.toString());
return builder.toString();
}
}
For this i also add adapter as well as arraylist.
but when i run this application api is not called perfectly..
hope anyone a]can help me..
here i add adapter and arraylist
Adapter
public Doctortype_Adapter(Context context, ArrayList<Doctortype_method> objects) {
super(context, R.layout.list_doctortype, objects);
this.context = context;
this.vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.actorList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
//View v = convertView;
View rowView;
ViewHolder vh;
if (convertView == null) {
rowView = vi.inflate(R.layout.list_doctortype, null);
setViewHolder(rowView);
} else {
rowView = convertView;
}
vh = (ViewHolder) rowView.getTag();
vh.title.setText(Html.fromHtml(actorList.get(position).gettitle()));
vh.subtitle.setText(Html.fromHtml(actorList.get(position).getsubtitle()));
/* String image=actorList.get(position).getid();
UrlImageViewHelper.setUrlDrawable(vh.dimage, image.toString(), R.drawable.no_img);*/
return rowView;
}
static class ViewHolder {
public TextView title, subtitle;
}
private void setViewHolder(View rowView) {
ViewHolder vh = new ViewHolder();
vh.title = (TextView) rowView.findViewById(R.id.tvProfileName);
vh.subtitle = (TextView) rowView.findViewById(R.id.tvDesc);
}
}
arraylist
public Doctortype_method( String title, String subtitle) {
super();
this.title = title;
this.subtitle = subtitle;
}
public String gettitle() {
return title;
}
public void settitle(String title) {
this.title = title;
}
public String getsubtitle()
{
return subtitle;
}
public void setsubtitle(String subtitle) {
this.subtitle = subtitle;
}
there is no error but when i run this code api is not called and i didnt get the output i want.
Thnx in advance..
if (status.equalsIgnoreCase("true")) is wrong because you getting status:1 so it is if (status.equalsIgnoreCase("1")) try this and then change this array = jobj.getJSONArray("response"); to array = jobj.getJSONArray("data"); your JSONArray key is "data"
And replace this also
actorsList.add(new Doctortype_method(jsonChildNode.optString("State id"),jsonChildNode.optString("State name")));
with
actorsList.add(new Doctortype_method(jsonChildNode.optString("countryID"),jsonChildNode.optString("vCountry")));
hope this helps. if this doesn't help feel free to ask
EDIT:
I cant understand what you want but have a look at this
-> you need to create baseAdapter for listview and set that adapter into the listview with your arraylist
FOR FETCHING YOUR ABOVE DATA YOU NEED TO DO BELOW CODE:
String data;//your entire JSON data as String
try {
JSONObject object = new JSONObject(data);
String status = object.getString("status");
JSONArray dataArray = object.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
JSONObject json1 = dataArray.getJSONObject(i);
String countryID = json1.getString("countryID");
String vCountry = json1.getString("vCountry");
}
} catch (JSONException e) {
e.printStackTrace();
}
Now if you want to show this vCountry in listview you have to add vCountry in ArrayList and then in listview.setAdapter you have to pass this ArrayList which is filled by vCountry. Hope you understand now. If you want adapter and listview code please check this link http://www.vogella.com/tutorials/AndroidListView/article.html
Finally i got the right answer.
May anyone get help from this in future.
ActivityClass.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_city_list_item);
lv_city = (ListView)findViewById(R.id.listView_city);
Bundle b=getIntent().getExtras();
city_stateid = b.getString("stateid");
city_statename=b.getString("stateName");
city_countryid=b.getString("country");
lv_city.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
page_cityname = cityist.get(position).getCityName();
SharedPreferences sp=getSharedPreferences("abc",MODE_WORLD_WRITEABLE);
SharedPreferences.Editor edit=sp.edit();
edit.putString("city_name", page_cityname);
edit.commit();
Toast.makeText(getApplicationContext(),"Selected city & State"+page_cityname + "-" +city_statename, Toast.LENGTH_LONG).show();
Intent i = new Intent(getApplicationContext(), NextActivity.class);
/*i.putExtra("cityname", page_cityname);*/
startActivity(i);
}
});
}
#Override
public void onResume() {
super.onResume();
params12 = new ArrayList<NameValuePair>();
params12.add(new BasicNameValuePair("type", city_type));
params12.add(new BasicNameValuePair("stateID", city_stateid));
params12.add(new BasicNameValuePair("countryID", city_countryid));
new Sync().execute();
}
class Sync extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected String doInBackground(Void... params) {
String obj;//new JSONArray();
try {
// obj=getJSONFromUrl("Your posting path", params11);
obj = getJSONFromUrl("http://52.26.35.210/api/web/v1/api-beautician/country-state-city", params12);
return obj;
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(final String result) {
super.onPostExecute(result);
Log.e("Result of geting data", "" + result);
try {
Log.e("Exam", "screen>>" + result);
JSONObject get_res = new JSONObject(result);
String status = get_res.getString("status");
Log.e("Exam", "screen33333>>" + status);
if (status.equalsIgnoreCase("1")) {
cityist = new ArrayList<city_method>();
JSONArray array = new JSONArray();
array = get_res.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
cityist.add(new city_method(array.getJSONObject(i).getString("cityID"),array.getJSONObject(i).getString("cityName")));
}
if (getApplicationContext() != null)
{
if (adapter == null)
{
adapter = new city_Adapter(getApplicationContext(),cityist);
lv_city.setAdapter(adapter);
} else {
adapter.notifyDataSetChanged();
}
}
}
} catch (Exception e) {
}
}
}
public String fetchResult(String urlString) throws JSONException {
StringBuilder builder;
BufferedReader reader;
URLConnection connection = null;
URL url = null;
String line;
builder = new StringBuilder();
reader = null;
try {
url = new URL(urlString);
connection = url.openConnection();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
}
//Log.d("DATA", builder.toString());
} catch (Exception e) {
}
//JSONArray arr=new JSONArray(builder.toString());
return builder.toString();
}
public String getJSONFromUrl(String url, List<NameValuePair> params) {
InputStream is = null;
String json = "";
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
//sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.e("JSON", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
}
Adapterclass.java
public class city_Adapter extends ArrayAdapter<city_method> {
ArrayList<city_method> citylist;
LayoutInflater vi;
Context context;
public city_Adapter(Context context, ArrayList<city_method> items) {
super(context, R.layout.list_doctortype, items);
this.context = context;
this.vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.citylist = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
//View v = convertView;
View rowView;
city_Adapter.ViewHolder vh;
if (convertView == null) {
rowView = vi.inflate(R.layout.program_list, null);
setViewHolder(rowView);
} else {
rowView = convertView;
}
vh = (city_Adapter.ViewHolder) rowView.getTag();
vh.cityid.setText((citylist.get(position).getCityID()));
vh.cityname.setText((citylist.get(position).getCityName()));
return rowView;
}
static class ViewHolder {
private TextView cityid,cityname;
}
private void setViewHolder(View rowView) {
ViewHolder vh = new ViewHolder();
vh.cityid = (TextView) rowView.findViewById(R.id.cityid);
vh.cityname = (TextView) rowView.findViewById(R.id.cityname);
rowView.setTag(vh);
}
}
Methodclass.java
public class city_method {
private String cityID,cityName;
public String getCityID() {
return cityID;
}
public void setCityID(String cityID) {
this.cityID = cityID;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public city_method(String cityID, String cityName) {
this.cityID = cityID;
this.cityName = cityName;
}
}

JSON returns data in one code and null in other

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);
}
}

Categories

Resources