In my program parseJsonData method is working but jsonObject and jsonArray is not executed. I cannot get a output.
package com.example.rajesh_pc.jsonapplication;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
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;
public class MainActivity extends AppCompatActivity {
ListView listView;
ProgressDialog progressDialog;
String url="http://demo.cogzideltemplates.com/anan/mobile/posts/viewall_Posts";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView= (ListView) findViewById(R.id.fruitsList);
progressDialog=new ProgressDialog(this);
progressDialog.setMessage("Loadiing");
progressDialog.show();
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String string) {
parseJsonData(url);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getApplicationContext(), "Some error occurred!!", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
RequestQueue requestQueue= Volley.newRequestQueue(MainActivity.this);
requestQueue.add(request);
}
void parseJsonData(String jsonstring)
{
try {
System.out.println("executinh parsejson method");
JSONObject jsonObject = new JSONObject(jsonstring);
System.out.println("executinh jsonobj method");
JSONArray jsonArray=jsonObject.getJSONArray("caption");
System.out.println("executinh jsonarraay method");
System.out.println("output===>"+jsonArray);
ArrayList arrayList=new ArrayList();
for (int i=0;i<jsonArray.length();i++)
{
arrayList.add(getString(i));
}
ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.activity_list_item,arrayList);
listView.setAdapter(arrayAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
progressDialog.dismiss();
}
}
Related
I am trying to get the data (List of Images and Names) from an Api using Volley into a recycler View but due to some reason I am only getting the list of names but unable to fetch the images corresponding to that name, and getting File Not Found Exception
This is the Main Activity
package com.example.bks;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
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.JsonArrayRequest;
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;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private static final String TAG ="tag";
RecyclerView recyclerView;
ProgressBar progressBar;
private List<CropModel> mList;
private cropAdapter cropAdapter;
private RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView=findViewById(R.id.recycleView);
progressBar=findViewById(R.id.progressBar);
cropAdapter= new cropAdapter(this, mList );
recyclerView.setLayoutManager(new LinearLayoutManager(this));
requestQueue=volleySingleton.getmInstance(this).getRequestQueue();
mList= new ArrayList<>();
fetchData();
}
private void fetchData() {
progressBar.setVisibility(View.VISIBLE);
String url= "http://bharatkrushiseva.in/api_user/getCropType";
JsonObjectRequest jsonObjectRequest= new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
progressBar.setVisibility(View.GONE);
try {
JSONArray jsonArray= response.getJSONArray("crop");
for(int i=0; i<jsonArray.length();i++){
JSONObject jsonObject= jsonArray.getJSONObject(i);
String name= jsonObject.getString("crop_name");
String image= jsonObject.getString("crop_image");
CropModel post = new CropModel(name,image);
mList.add(post);
}
cropAdapter adapter = new cropAdapter(MainActivity.this,mList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.GONE);
Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}){
#Override
public Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> params= new HashMap<>();
params.put("language","en");
return params;
}
};
requestQueue.add(jsonObjectRequest);
}
}
This is the Adapter Class
package com.example.bks;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
public class cropAdapter extends RecyclerView.Adapter<cropAdapter.Viewholder> {
private Context context;
private List<CropModel> cropModels;
public cropAdapter(Context context, List<CropModel> cropModels) {
this.context = context;
this.cropModels = cropModels;
}
#NonNull
#Override
public Viewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(context).inflate(R.layout.crop_view,parent,false);
return new cropAdapter.Viewholder(view);
}
#Override
public void onBindViewHolder(#NonNull Viewholder holder, int position) {
CropModel cropModel= cropModels.get(position);
holder.cropName.setText(cropModel.getCrop_name());
Glide.with(context).load(cropModel.getCrop_image()).into(holder.cropImage);
}
#Override
public int getItemCount() {
return cropModels.size() ;
}
public class Viewholder extends RecyclerView.ViewHolder {
TextView cropName;
ImageView cropImage;
public Viewholder(#NonNull View itemView) {
super(itemView);
cropImage=itemView.findViewById(R.id.Cropimage);
cropName=itemView.findViewById(R.id.cropName);
}
}
}
This is my Model Class
package com.example.bks;
public class CropModel {
private String crop_name;
private String crop_image;
public CropModel(String crop_name, String crop_image) {
this.crop_name = crop_name;
this.crop_image = crop_image;
}
public String getCrop_name() {
return crop_name;
}
public void setCrop_name(String crop_name) {
this.crop_name = crop_name;
}
public String getCrop_image() {
return crop_image;
}
public void setCrop_image(String crop_image) {
this.crop_image = crop_image;
}
}
This is the Volley Singleton Class
package com.example.bks;
import android.content.Context;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
public class volleySingleton {
private RequestQueue requestQueue;
private static volleySingleton mInstance;
private volleySingleton(Context context) {
requestQueue= Volley.newRequestQueue(context.getApplicationContext());
}
public static synchronized volleySingleton getmInstance(Context context){
if(mInstance==null){
mInstance=new volleySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue(){
return requestQueue;
}
}
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
package com.example.signup2;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
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;
public class Main2Activity extends AppCompatActivity {
ListView listView;
ArrayList<UserData> arrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
listView = findViewById(R.id.listview);
fetchData();
}
public void fetchData()
{
StringRequest stringRequest = new StringRequest(Request.Method.GET, "https://androidwork2132.000webhostapp.com/fetch.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("users");
for (int i = 0;i < jsonArray.length(); i++)
{
UserData userData = new UserData(jsonArray.getJSONObject(i).getString("id"),jsonArray.getJSONObject(i).getString("username"),
jsonArray.getJSONObject(i).getString("email"),jsonArray.getJSONObject(i).getString("password"));
arrayList.add(userData);
}
CustomAdapter customAdapter = new CustomAdapter();
listView.setAdapter(customAdapter);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Main2Activity.this,error.getLocalizedMessage(),Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(Main2Activity.this);
requestQueue.add(stringRequest);
}
class CustomAdapter extends BaseAdapter
{
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = getLayoutInflater().inflate(R.layout.listviewitem,null);
TextView id,username,email,password;
id = findViewById(R.id.id);
username = findViewById(R.id.username);
email = findViewById(R.id.email);
password =findViewById(R.id.password);
id.setText(arrayList.get(position).getId());
username.setText(arrayList.get(position).getUsername());
email.setText(arrayList.get(position).getEmail());
password.setText(arrayList.get(position).getPassword());
return view;
}
}
}
MainActivity.java
W/System.err: org.json.JSONException: Value [] at 0 of type org.json.JSONArray cannot be converted to JSONObject
W/System.err: at org.json.JSON.typeMismatch(JSON.java:101)
at org.json.JSONArray.getJSONObject(JSONArray.java:525)
at com.example.signup2.Main2Activity$1.onResponse(Main2Activity.java:54)
at com.example.signup2.Main2Activity$1.onResponse(Main2Activity.java:43)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:82)
W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:29)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:226)
at android.app.ActivityThread.main(ActivityThread.java:7208)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:499)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:942)
My error
I want to fetch the records from database in android.For this purpose i have tried this code for fetching the records from database.I have used volley library which is working fine the error is converting the at value[] 0 of W/System.err: org.json.JSONException: Value [] at 0 of type org.json.JSONArray cannot be converted to JSONObject
W/System.err: at org.json.JSON.typeMismatch(JSON.java:101)
i have mentioned this completely.
There is an issue with the JSON reponse returned by the api
https://androidwork2132.000webhostapp.com/fetch.php
The first item in users array in JSON response is an array, it must be an object like rest of the objects
{"users":[[], // This array here, it should be an object like rest of the objects.
{"0":"1","id":"1","1":"","username":"","2":"","email":"","3":"","password":""},
{"0":"2","id":"2","1":"","username":"","2":"","email":"","3":"","password":""},
{"0":"3","id":"3","1":"","username":"","2":"","email":"","3":"","password":""},
{"0":"4","id":"4","1":"ABC ","username":"ABC ","2":"abc#gmail.com","email":"abc#gmail.com","3":"97532","password":"97532"},
{"0":"5","id":"5","1":"ABC ","username":"ABC ",
"2":"abx#gmail.com","email":"abx#gmail.com","3":"123345","password":"123345"}]}
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'
I'm new to android app programming. I have a webview that shows the post content, but I am only getting text and images, please tell me how to change loadData to loadUrl
My classes :
1. MainActivity.java
package com.a000webhostapp.androidgrid.androidgridapp;
import android.animation.Animator;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.DownloadListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
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 com.google.gson.Gson;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity{
Button layout;
RelativeLayout fragmentContent, homeContent;
final static String urlAddress = "https://androidgrid.000webhostapp.com/index.php/feed/";
String url = "http://androidgrid.000webhostapp.com/wp-json/wp/v2/posts?filter[posts_per_page]=10&fields=id,title,link";
List<Object> list;
Gson gson;
ProgressDialog progressDialog;
ListView postList;
Map<String,Object> mapPost;
Map<String,Object> mapTitle;
int postID;
String postTitle[];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
postList = (ListView)findViewById(R.id.postList);
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
gson = new Gson();
list = (List) gson.fromJson(s, List.class);
postTitle = new String[list.size()];
for(int i=0;i<list.size();++i){
mapPost = (Map<String,Object>)list.get(i);
mapTitle = (Map<String, Object>) mapPost.get("title");
postTitle[i] = (String) mapTitle.get("rendered");
}
postList.setAdapter(new ArrayAdapter(MainActivity.this,android.R.layout.simple_list_item_1,postTitle));
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(MainActivity.this, "Some error occurred", Toast.LENGTH_LONG).show();
}
});
RequestQueue rQueue = Volley.newRequestQueue(MainActivity.this);
rQueue.add(request);
postList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mapPost = (Map<String,Object>)list.get(position);
postID = ((Double)mapPost.get("id")).intValue();
Intent intent = new Intent(getApplicationContext(),Post.class);
intent.putExtra("id", ""+postID);
startActivity(intent);
}
});
}
}
2. Post.java
package com.a000webhostapp.androidgrid.androidgridapp;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
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 com.google.gson.Gson;
import java.util.Map;
public class Post extends AppCompatActivity {
TextView title;
WebView content;
ProgressDialog progressDialog;
Gson gson;
Map<String, Object> mapPost;
Map<String, Object> mapTitle;
Map<String, Object> mapContent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.post);
final String id = getIntent().getExtras().getString("id");
title = (TextView) findViewById(R.id.title);
content = (WebView)findViewById(R.id.content);
progressDialog = new ProgressDialog(Post.this);
progressDialog.setMessage("Loading...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
String url = "http://androidgrid.000webhostapp.com/wp-json/wp/v2/posts/"+id+"?fields=title,content";
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
gson = new Gson();
mapPost = (Map<String, Object>) gson.fromJson(s, Map.class);
mapTitle = (Map<String, Object>) mapPost.get("title");
mapContent = (Map<String, Object>) mapPost.get("content");
title.setText(mapTitle.get("rendered").toString());
content.loadData(mapContent.get("rendered").toString(),"text/html","UTF-8");
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
progressDialog.dismiss();
Toast.makeText(Post.this, id, Toast.LENGTH_LONG).show();
}
});
RequestQueue rQueue = Volley.newRequestQueue(Post.this);
rQueue.add(request);
}
}
Your filtered the result. You can use this URL to get full post:
http://yourwebsite.com/wp-json/wp/v2/posts/
You can also get by categories:
http://yourwebsite.com/wp-json/wp/v2/posts/?categories=1
As you see you had to pass category id and all categories can get by:
http://yourwebsite.com/wp-json/wp/v2/categories/
You can also get paged result by:
http://yourwebsite.com/wp-json/wp/v2/posts/?categories=1&page=2
If you wan to get post images, check this question and if you want to implement OAuth for better security for your apis check this out. I hope this helps.