Implementing if statement directly to Arraylist [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
I am using RecyclerView and CardView. I want the sysytem to choose which ImageView to display by circumstances from the JSON. How should I do it? I implemented the if statement but it seems like the statement is not working. Could someone give me an advice. This is my first time writing a parsing program. I don't know much about it.
package com.morimoku.location_activity;
import android.app.DownloadManager;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class favaoritesFragment extends Fragment {
public static TextView data;
private RecyclerView.Adapter mAdapter;
private RequestQueue mQueue;
private RecyclerView.LayoutManager mLayoutManager;
int i1;
int i2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState){
View view = inflater.inflate(R.layout.fragment_favorites,container,false);
mQueue = Volley.newRequestQueue(getActivity());
ArrayList<Status> statusArrayList = new ArrayList<>();
statusArrayList.add(new Status(R.drawable.ic_action_name,"Line 1", (i1 == 0)?
R.drawable.ic_check_box_black_24dp: R.drawable.ic_warning_black_24dp));
statusArrayList.add(new Status(R.drawable.ic_action_name,"Line 2", (i2 == 0)?
R.drawable.ic_check_box_black_24dp: R.drawable.ic_warning_black_24dp));
mAdapter = new RecyclerAdapter(statusArrayList);
RecyclerView mRecyclerView = view.findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));//listView.setAdapter(adapter);
mRecyclerView.setAdapter(mAdapter);
return view;
}
private void jsonParse() {
String url = ("URL");
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("odpt.TrainInformation:Line 1");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject negishi = jsonArray.getJSONObject(i);
String negishis = negishi.getString("odpt:trainInformationText");
if (negishis.equals( "operating normally")) {
i1 = 0;
} else {
i1 = 1;
}
}
JSONArray jsonArray1 = response.getJSONArray("odpt.TrainInformation:Line 2");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject negishi2 = jsonArray.getJSONObject(i);
String negishis2 = negishi2.getString("odpt:trainInformationText");
if (negishis2 .equals( "operating normally")) {
i2 = 0;
} else {
i2 = 1;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
}}

statusArrayList.add(new Status(R.drawable.ic_action_name,"keihin",
(i1 == 0? R.drawable.common_google_signin_btn_icon_dark_focused:
R.drawable.common_google_signin_btn_icon_dark_focused));

Related

Draw Route in RecyclerView with GoogleMaps

I´m trying to draw a route in severel google maps using a reclycerview, but i don't know why doesn´t draw in the first map, but in the other draw correctly.
I´m using Library Volley to get the data.
ReclycerView:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import com.directions.route.AbstractRouting;
import com.directions.route.Route;
import com.directions.route.RouteException;
import com.directions.route.Routing;
import com.directions.route.RoutingListener;
import com.example.crossonme.Dependencias.Alertas.Alerta;
import com.example.crossonme.Dependencias.DB.EventosItem;
import com.example.crossonme.Login_Register;
import com.example.crossonme.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MapStyleOptions;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.material.snackbar.Snackbar;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> implements OnMapReadyCallback, RoutingListener{
Context context;
public static ArrayList<EventosItem> eventosItemArrayList = new ArrayList<>();
private OnClick mOnClick;
GoogleMap mMap;
MapView mMapView;
int id, Position;
private List<Polyline> polylines = null;
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView tvNome, tvDescricao, dtData;
OnClick onClick;
MyViewHolder(View view, OnClick onClick) {
super(view);
tvNome = view.findViewById(R.id.evitem_nome);
tvDescricao = view.findViewById(R.id.evitem_descricao);
dtData = view.findViewById(R.id.evitem_data);
mMapView = view.findViewById(R.id.evitem_map);
this.onClick = onClick;
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onClick.onItemClick(getAdapterPosition());
}
}
public MyAdapter(ArrayList<EventosItem> eventosItemArrayList, OnClick onClick) {
this.eventosItemArrayList = eventosItemArrayList;
this.mOnClick = onClick;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.evento_item, null, true);
context = parent.getContext();
return new MyViewHolder(view, mOnClick);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Position = position;
mMapView.onCreate(null );
mMapView.onResume();
Findroutes(eventosItemArrayList.get(Position).getComecoEv(), eventosItemArrayList.get(Position).getFimEv());
Log.e("TAG", ""+ Position );
mMapView.getMapAsync(this);
id = eventosItemArrayList.get(position).getIdEv();
holder.tvNome.setText(eventosItemArrayList.get(position).getNomeEv());
holder.tvDescricao.setText(eventosItemArrayList.get(position).getDescricaoEv());
holder.dtData.setText(eventosItemArrayList.get(position).getDataEv());
}
#Override
public int getItemCount() {
return eventosItemArrayList.size();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap= googleMap;
googleMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(context, R.raw.map_theme));
LatLng Portugal = new LatLng(39.399872, -8.224454);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Portugal, 6));
}
public interface OnClick{
void onItemClick(int position);
}
public void Findroutes(LatLng Start, LatLng End)
{
Routing routing = new Routing.Builder()
.travelMode(AbstractRouting.TravelMode.DRIVING)
.withListener(this)
.alternativeRoutes(true)
.waypoints(Start, End)
.key("AIzaSyDzsi_tYj6jhR2CiPx9g-d7EEc8BRb6N7g")
.build();
routing.execute();
}
//Routing call back functions.
#Override
public void onRoutingFailure(RouteException e) {
}
#Override
public void onRoutingStart() {
}
#Override
public void onRoutingSuccess(ArrayList<Route> route, int shortestRouteIndex) {
PolylineOptions polyOptions = new PolylineOptions();
LatLng polylineStartLatLng=null;
LatLng polylineEndLatLng=null;
polylines = new ArrayList<>();
for (int i = 0; i <route.size(); i++) {
if(i==shortestRouteIndex)
{
polyOptions.color(Color.parseColor("#FF8E06"));
polyOptions.width(10);
polyOptions.addAll(route.get(shortestRouteIndex).getPoints());
Polyline polyline = mMap.addPolyline(polyOptions);
polylineStartLatLng=polyline.getPoints().get(0);
int k=polyline.getPoints().size();
polylineEndLatLng=polyline.getPoints().get(k-1);
polylines.add(polyline);
}
}
MarkerOptions endMarker = new MarkerOptions();
endMarker.position(polylineEndLatLng);
endMarker.title("Destino");
endMarker.icon(bitmapDescriptorFromVector(context, R.drawable.dt_fim));
mMap.addMarker(endMarker);
MarkerOptions beginMarker = new MarkerOptions();
beginMarker.position(polylineStartLatLng);
beginMarker.title("Inicio");
beginMarker.icon(bitmapDescriptorFromVector(context, R.drawable.dt_inicio));
mMap.addMarker(beginMarker);
}
#Override
public void onRoutingCancelled() {
}
private BitmapDescriptor bitmapDescriptorFromVector(Context context, #DrawableRes int vectorDrawableResourceId) {
Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorDrawableResourceId);
vectorDrawable.setBounds(0, 0, vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight());
Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
vectorDrawable.draw(canvas);
return BitmapDescriptorFactory.fromBitmap(bitmap);
}
}
MainActivity
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.crossonme.Dependencias.Alertas.Alerta;
import com.example.crossonme.Dependencias.DB.EventosItem;
import com.example.crossonme.Dependencias.DB.SharedPrefManager;
import com.example.crossonme.Dependencias.DB.URLs;
import com.example.crossonme.Dependencias.DB.User;
import com.example.crossonme.Dependencias.DB.VolleySingleton;
import com.example.crossonme.Dependencias.MyAdapter;
import com.example.crossonme.R;
import com.google.android.gms.maps.model.LatLng;
import com.google.gson.JsonObject;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Eventos extends android.app.Activity implements View.OnClickListener, MyAdapter.OnClick
{
public static ArrayList<EventosItem> eventosItemArrayList = new ArrayList<>();
EventosItem eventosItem;
LatLng Inicio, Fim;
MyAdapter adapter;
#Override
public void onCreate(android.os.Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.eventos);
eventosItemArrayList.clear();
adapter = new MyAdapter(eventosItemArrayList, this);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
mLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.ev_ScrollAtual);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setNestedScrollingEnabled(true);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_EVENTOS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting response to json object
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++){
JSONObject object = array.getJSONObject(i);
String[] latlongIni = object.getString("comeco").split(",");
String[] latlongFim = object.getString("fim").split(",");
Inicio = new LatLng(Double.parseDouble(latlongIni[0]), Double.parseDouble(latlongIni[1]));
Fim = new LatLng(Double.parseDouble(latlongFim[0]), Double.parseDouble(latlongFim[1]));
eventosItem = new EventosItem(object.getString("nome"), object.getString("tipo"),object.getString("descricao"),object.getString("nome_empresa"),object.getInt("id"),object.getString("data"),Inicio,Fim);
eventosItemArrayList.add(eventosItem);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
new Alerta.MensagemAlerta(Eventos.this, "Erro", error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
#Override
public void onClick(View v) {
}
#Override
public void onItemClick(int position) {
new Alerta.MensagemAlerta(Eventos.this, "Erro", String.valueOf(position));
}
}
This is for a project, i have tryed several thing's but not helped.
I hope someone can help me.
David

Get an error : com.android.volley.ParseError: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray

I try to get data from the database via API but the recyclerview doesn't display anything and the log displays an error.
This is my code
Fragment
package com.example.hp.retailmakanan;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.example.hp.retailmakanan.Model.MenuModel;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class FragHome extends Fragment {
RecyclerView recV;
BottomNavigationView top_navigation;
HomeAdapter listAdapter;
List<MenuModel> listMenu= new ArrayList<>();
private BottomNavigationView.OnNavigationItemSelectedListener onNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment sfragment = null;
switch (menuItem.getItemId()) {
case R.id.nav_noodle:
recV.setAdapter(listAdapter);
break;
case R.id.nav_beverage:
recV.setAdapter(listAdapter);
break;
case R.id.nav_toping:
recV.setAdapter(listAdapter);
break;
case R.id.nav_cari:
recV.setAdapter(listAdapter);
break;
}
return false;
}
};
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.act_home, container, false);
recV = (RecyclerView) v.findViewById(R.id.rec_ramen);
getData();
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recV.setLayoutManager(layoutManager);
listAdapter = new HomeAdapter(listMenu, getActivity());
recV.setAdapter(listAdapter);
top_navigation = (BottomNavigationView) v.findViewById(R.id.top_nav);
top_navigation.setOnNavigationItemSelectedListener(onNavigationItemSelectedListener);
return v;
}
this is the code that i used to get data
private void getData() {
String url ="https://waggish-requisition.000webhostapp.com/GetAllMenu.php";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
listMenu.clear();
for (int i = 0; i < response.length(); i++) {
try {
Log.d("menu",response.toString());
JSONObject jsonObject = response.getJSONObject(i);
String id_menu = jsonObject.getString("id");
String nama_menu = jsonObject.getString("nama_menu");
String deskripsi = jsonObject.getString("deskripsi");
int harga = jsonObject.getInt("harga");
MenuModel menus = new MenuModel(id_menu,nama_menu,deskripsi,harga);
listMenu.add(menus);
System.out.println(menus);
//Toast.makeText(this,"Download data "+i,Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
Log.d("menu",e.toString());
}
listAdapter.notifyDataSetChanged();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", error.toString());
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(jsonArrayRequest);
}
}
Adapter
package com.example.hp.retailmakanan;
import android.content.Context;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.hp.retailmakanan.Model.MenuModel;
import java.util.Arrays;
import java.util.List;
public class HomeAdapter extends RecyclerView.Adapter {
private List<MenuModel> menus;
private Context context;
public HomeAdapter(List<MenuModel> menus, Context context) {
this.context = context;
this.menus = menus;
//System.out.println(menus);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recv_desain, viewGroup, false);
return new ListViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int pos) {
}
#Override
public int getItemCount() {
return menus.size();
}
public class ListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView mText,txt2, txt3, txtQty;
ImageView img;
Button btnMin, btnPlus;
int x;
public ListViewHolder(View itemView){
super(itemView);
mText = itemView.findViewById(R.id.text_item);
txt2 = itemView.findViewById(R.id.text_item2);
txt3 = itemView.findViewById(R.id.textView3);
img = itemView.findViewById(R.id.image_item);
btnMin = itemView.findViewById(R.id.buttonMinMenu);
btnPlus = itemView.findViewById(R.id.buttonPlusMenu);
txtQty = itemView.findViewById(R.id.textQtyMenu);
itemView.setOnClickListener(this);
}
public void bindView (int pos){
x=0;
MenuModel model = menus.get(pos);
mText.setText(model.getNama_menu());
txt2.setText(model.getDeskripsi());
txt3.setText(model.getHarga());
//img.setImageResource(DataMenu.picture[pos]);
txtQty.setText(String.valueOf(x));
btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
x++;
txtQty.setText(String.valueOf(x));
}
});
btnMin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
x--;
if (x<=0){
x=0;
txtQty.setText(String.valueOf(x));
}else if (x>0){
txtQty.setText(String.valueOf(x));
}
}
});
}
#Override
public void onClick(View v) {
}
}
}
And this is my php code
<?php
require_once('connection.php');
//public $mServerName;
//public $mConnectionInfo;
//public $conn;
//Create query to retrieve all contacts
$query = "SELECT * FROM menu";
$stmt = mysqli_query($conn, $query);
if (!$stmt)
{
//Query failed
echo 'Query failed';
}
else
{
$menus= array(); //Create an array to hold all of the contacts
//Query successful, begin putting each contact into an array of contacts
while ($row = mysqli_fetch_array($stmt)) //While there are still contacts
{
//Create an associative array to hold the current contact
//the names must match exactly the property names in the contact class in our C# code.
$menu= array("id" => $row['id_menu'],
"deskripsi" => $row['Deskripsi'],
"nama_menu" => $row['nm_menu'],
"harga" => $row['harga_menu'],
"ImageUrl" =>$row['gambar']
);
//Add the contact to the contacts array
array_push($menus, $menu);
}
//Echo out the contacts array in JSON format
echo json_encode($menus);
}
?>
I changed JSONObject to JSONArray, but that caused many other errors. I am a beginner please help me. I really don't know what to do :(

unexpected response code 401 for URL

package com.example.murarilal.volley;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
RequestQueue queue;
ListView listView;
List<Hero> heroList;
private String url="API_KEY";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
queue= Volley.newRequestQueue(this);
home();
listView = (ListView) findViewById(R.id.listView);
heroList = new ArrayList<>();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent=new Intent(getApplicationContext(),ArticleActivity.class);
intent.putExtra("description",url);
startActivity(intent);
}
});
}
public void home()
{
JsonObjectRequest request =new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject obj = new JSONObject(String.valueOf(response));
JSONArray array = obj.getJSONArray("articles");
for (int i = 0; i < array.length(); i++) {
Hero hero=new Hero( (String) array.getJSONObject(i).get("title"),(String) array.getJSONObject(i).get("urlToImage"));
heroList.add(hero);
}
ListViewAdapter adapter = new ListViewAdapter(heroList, getApplicationContext());
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(request);
}
}
package com.example.murarilal.volley;
import android.content.Intent;
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.webkit.WebView;
import android.webkit.WebViewClient;
public class ArticleActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_article);
String url="https://newsapi.org/v1/articles?source=techcrunch&apiKey=59b308aec9f242fe98b527ab9ba93199";
WebView webView=(WebView)findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
Intent intent=getIntent();
webView.loadDataWithBaseURL(url,null,intent.getStringExtra("description"),"text/html","UTF-8");
webView.loadUrl(url);
}
}
https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=d6eaad863cc640a7a6864d18196bea9e
I'm trying to fetch data from the above url but it returns an unexpected 401 response code. I checked the url and it's perfectly valid but the my code gives this error. when the emulator starts it shows blank activity
this the log error
11-17 16:20:20.804 14350-14350/com.example.murarilal.volley
W/System.err: com.android.volley.AuthFailureError 11-17 16:20:20.804
14350-14350/com.example.murarilal.volley W/System.err: at
com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:141)
11-17 16:20:20.804 14350-14350/com.example.murarilal.volley
W/System.err: at
com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:105)
public class MainActivity extends AppCompatActivity {
RequestQueue queue;
ListView listView;
List<Hero> heroList;
private String url="https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=d6eaad863cc640a7a6864d18196bea9e";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
queue= Volley.newRequestQueue(this);
home();
listView = (ListView) findViewById(R.id.listView);
heroList = new ArrayList<>();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
/* Intent intent=new Intent(getApplicationContext(),ArticleActivity.class);
intent.putExtra("description",url);
startActivity(intent);*/
}
});
}
public void home()
{
JsonObjectRequest request =new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject obj = new JSONObject(String.valueOf(response));
JSONArray array = obj.getJSONArray("articles");
for (int i = 0; i < array.length(); i++) {
Hero hero=new Hero( (String) array.getJSONObject(i).get("title"),(String) array.getJSONObject(i).get("urlToImage"));
Log.d("title ", String.valueOf(array.getJSONObject(i).get("title")));
Log.d("urlToImage ", String.valueOf(array.getJSONObject(i).get("urlToImage")));
heroList.add(hero);
}
ListViewAdapter adapter = new ListViewAdapter(heroList, getApplicationContext());
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(request);
}
}
Try to use URLConnection instead of volley.
401 indicates of have Unauthorized access to the given URL
I tried both api V1 And V2 with volley and got status code 200 and the data matches with the data shown when the request is made from a browser.
To help Can you add Logs and post it over here
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG,error.networkResponse.toString());
error.printStackTrace();
}
});
Have you tried adding this line in your gradle file.
I've implemented your code, the data is being called properly.
compile 'com.mcxiaoke.volley:library-aar:1.0.0'

Sort Array in Recyclerview (Java, Android)

package com.example.sander.app;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by Sander on 6-4-2017.
*/
public class RecycleFrame extends Fragment {
ArrayList<String> names = new ArrayList<>();
ArrayList<String> cPoints = new ArrayList<>();
ArrayList<String> code = new ArrayList<>();
ArrayList<String> latitude = new ArrayList<>();
ArrayList<String> longitude = new ArrayList<>();
GPSTracker gps;
ArrayList<Double> dLatitude = new ArrayList<>();
ArrayList<Double> dLongitude = new ArrayList<>();
ArrayList<Float> distance = new ArrayList<>();
ArrayList<Data> dataList = new ArrayList<>();
public RecycleFrame() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fragment_view, menu);
super.onCreateOptionsMenu(menu,inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Integer id = item.getItemId();
if(id == R.id.action_A_Z){
//Sorts the garages from A to Z
Collections.sort(names);
//Refreshes the fragment
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.detach(this).attach(this).commit();
return true;
}
else if(id == R.id.action_Z_A){
//Sorts the garages from Z to A
Collections.reverse(names);
//Refreshes the fragment
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.detach(this).attach(this).commit();
return true;
}
else if (id == R.id.short_distance){
Collections.sort(distance);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.detach(this).attach(this).commit();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_recycle, container, false);
final RecyclerView VRecyclerView = (RecyclerView) view.findViewById(R.id.rv_recycler_view);
RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());
String url= "http://test.dontstealmywag.ga/api/parkgarage_all.php";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Do something with the response
try{
JSONObject o = new JSONObject(response);
JSONArray values=o.getJSONArray("");
if(names.size() == 0) {
for (int i = 0; i < values.length(); i++) {
JSONObject jsonObject = values.getJSONObject(i);
dataList.add(new Data(jsonObject.getString("parkgarage_name"), jsonObject.getString("charging_capcatity"), jsonObject.getDouble("langitude"),
jsonObject.getDouble("longitude"), jsonObject.getString("parkgarage_code"), distance.get(i)));
//names.add(jsonObject.getString("parkgarage_name"));
//cPoints.add(jsonObject.getString("charging_capacity"));
//code.add(jsonObject.getString("parkgarage_code"));
//latitude.add(jsonObject.getString("langitude"));
//longitude.add(jsonObject.getString("longitude"));
dLatitude.add(jsonObject.getDouble("langitude"));
dLongitude.add(jsonObject.getDouble("longitude"));
}
}
} catch (JSONException ex){}
gps = new GPSTracker(getActivity());
//check if gps is on
if(!gps.canGetLocation()){
gps.showSettingsAlert();
}
Location myLocation = new Location("");
myLocation.setLatitude(gps.getLatitude());
myLocation.setLongitude(gps.getLongitude());
for(int z = 0; z < latitude.size(); z++){
Location parkingGarage = new Location("");
parkingGarage.setLatitude(dLatitude.get(z));
parkingGarage.setLongitude(dLongitude.get(z));
distance.add(myLocation.distanceTo(parkingGarage)/1000);
}
VRecyclerView.setHasFixedSize(true);
//RecycleAdapter adapter = new RecycleAdapter(names, cPoints, code, latitude, longitude, distance);
RecycleAdapter adapter = new RecycleAdapter(dataList);
VRecyclerView.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
VRecyclerView.setLayoutManager(llm);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
});
rq.add(stringRequest);
return view;
}
}
This is my RecycleFrame code, below is my RecyclerAdapter code
package com.example.sander.app;
import android.app.Fragment;
import android.media.Image;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.lang.reflect.Array;
import java.util.ArrayList;
/**
* Created by Sander on 6-4-2017.
*/
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.MyViewHolder> {
ArrayList<Data> ArrayListData;
public static class MyViewHolder extends RecyclerView.ViewHolder{
public CardView mCardView;
public TextView TextViewNames;
public MyViewHolder(View v){
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
TextViewNames = (TextView) v.findViewById(R.id.text_view_names);
}
}
public RecycleAdapter(ArrayList<Data> names){
ArrayListData = names;
//ArrayCharging= cPoints;
//ArrayCode = code;
//ArrayLatitude = latitude;
//ArrayLongitude = longitude;
//ArrayDistance = distance;
}
#Override
public RecycleAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_card_view, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position){
holder.TextViewNames.setText(String.valueOf(ArrayListData.get(position)));
//holder.TextViewNames.setText("Naam: " + ArrayNames.get(position));
//holder.TextViewCharging.setText("Oplaadpunten: " + ArrayCharging.get(position));
//holder.TextViewCode.setText("Code: " + ArrayCode.get(position));
//holder.TextViewLatitude.setText("Positie: (" + ArrayLatitude.get(position) + ", " + ArrayLongitude.get(position)+ ")");
//holder.TextViewDistance.setText(String.valueOf(ArrayDistance.get(position)));
//holder.mImageView.setImageResource(R.drawable.ic_local_parking_black_24dp);
}
#Override
public int getItemCount() { return ArrayListData.size(); }
}
What I want is the following: I want to be able to press a item in a 3 dot menu and sort it from A to Z, Z to A & sort in on distance to the certain location. Sorting works correct (except for the distance but I can fix that myself). The only problem is that when I sort from A to Z or Z to A or distance the code & name & cPoints are not matching anymore. Does anyone know how to fix this?
As per you code you have multiple arraylist for name, distance, cpoint and when you sort one list the mapping between sorted list and all others list lost.
To fix this you have to keep the mapping between all whenever you sort based on attribute.
Better create a custom class with fields like name, distance, cpoint.... and whenever you sort on one attribute sort the list of custom objects. By this way mapping between multiple list is not lost.
There is another inefficient approach to solve the problem. But I will not recommend.
Try to sort the 4 array simultaneously based on one key. Like if you want to sort based on name, try to implement the selection sort on name array and on swapping swap elements in all four array to maintain the mapping between all four. Performance of sorting is not good in this solution. To implement this refer How to sort multiple ArrayLists based off order of another?

Populate recycle adapter from controller class

I'm trying to populate a recycle adapter from a controller class, to split the logic in the app. But I can't seem to get it working.. Do to the request is running on another thread, the view is not updated before it is shown. What am I doing wrong ?
FragmentClass:
package lassebjoerklund.homecontrol.views.fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import org.json.JSONArray;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import lassebjoerklund.homecontrol.R;
import lassebjoerklund.homecontrol.adapters.FridgeFragmentOverViewAdapter;
import lassebjoerklund.homecontrol.controllers.FridgeController;
import lassebjoerklund.homecontrol.decorations.DividerItemDecoration;
import lassebjoerklund.homecontrol.model.Product;
import lassebjoerklund.homecontrol.utils.FragmentUtil;
/**
* Created by zigge on 29-Mar-16.
*/
public class FridgeFragmentOverView extends Fragment {
private final FridgeController fridgeController = new FridgeController();
private RecyclerView recyclerView;
private LinkedList<String> types;
private FridgeFragmentOverViewAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_overview_layout, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.productOverviewRecycleView);
recyclerView.setHasFixedSize(true);
RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST);
recyclerView.addItemDecoration(itemDecoration);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(layoutManager);
adapter = new FridgeFragmentOverViewAdapter(fridgeController.getProductsTypes());
recyclerView.setAdapter(adapter);
return v;
}
#Override
public void onResume() {
super.onResume();
fridgeController.refresh(getContext(), adapter);
}
}
Controller Class:
package lassebjoerklund.homecontrol.controllers;
import android.content.Context;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import lassebjoerklund.homecontrol.adapters.FridgeFragmentOverViewAdapter;
import lassebjoerklund.homecontrol.interfaces.OnSucsess;
import lassebjoerklund.homecontrol.model.Product;
/**
* Created by zigge on 29-Mar-16.
*/
public class FridgeController implements OnSucsess {
private RequestQueue rQueue;
private ArrayList<Product> products;
private List<String> productsTypes;
public ArrayList<Product> getProducts() {
return products;
}
public List<String> getProductsTypes() {
return productsTypes;
}
public void refresh(Context context, final FridgeFragmentOverViewAdapter adapter) {
String fetchProducts = "http://87.52.28.25:900/index.php";
rQueue = Volley.newRequestQueue(context);
final JsonArrayRequest getProductsRequest = new JsonArrayRequest(fetchProducts, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
products = new ArrayList<>();
productsTypes = new ArrayList<>();
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = (JSONObject) response.get(i);
String barcode = jsonObject.getString("code");
String name = jsonObject.getString("name");
String ex_date = jsonObject.getString("ex_date");
String add_date = jsonObject.getString("add_date");
String type = jsonObject.getString("type");
Product product = new Product(barcode, name, ex_date, add_date, type);
products.add(product);
}
} catch (JSONException e) {
e.printStackTrace();
}
if (products.size() != 0) {
for (int i = 0; i < products.size(); i++) {
if (!productsTypes.contains(products.get(i).getType())) {
productsTypes.add(products.get(i).getType());
}
}
}
getProductsOnsucsess(adapter);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
rQueue.add(getProductsRequest);
}
#Override
public void getProductsOnsucsess(FridgeFragmentOverViewAdapter adapter) {
adapter.refreshAdapter(productsTypes);
}
}
Adapter:
package lassebjoerklund.homecontrol.adapters;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import lassebjoerklund.homecontrol.R;
import lassebjoerklund.homecontrol.model.Product;
/**
* Created by zigge on 29-Mar-16.
*/
public class FridgeFragmentOverViewAdapter extends RecyclerView.Adapter {
private List<String> types;
public FridgeFragmentOverViewAdapter(List<String> types) {
this.types = types;
}
#Override
public int getItemCount() {
return 0;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_overview_card_layout, null);
return new ProductsGroupedHolder(v);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
}
public class ProductsGroupedHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView tvTypeOfProduct, tvCount, tvExpired;
public ProductsGroupedHolder(View itemView) {
super(itemView);
tvTypeOfProduct = (TextView) itemView.findViewById(R.id.tvTypeOfProduct);
tvCount = (TextView) itemView.findViewById(R.id.tvCount);
tvExpired = (TextView) itemView.findViewById(R.id.tvExpired);
}
#Override
public void onClick(View v) {
}
}
public void refreshAdapter(List<String> types) {
if(this.types != null) {
this.types.clear();
this.types = types;
notifyDataSetChanged();
}else {
this.types = types;
notifyDataSetChanged();
}
}
}
Try calling:
adapter.notifyDataSetChanged();
after updating it.
Edit 1:
Return actual size of adapter items in getItemCount() as #prathamkesarkar said.
Simple looks like you have set the getItemType() method return 0.
That method determines how much item your RecyclerView have.
#Override
public int getItemCount() {
return type.size();
}

Categories

Resources