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'
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;
}
}
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"}]}
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();
}
}
I have this weird periodic error, when i boot the app, and the onCreate is called, but the CardView is not showing anything. Other times I do the exact same thing, booting the app, and the CardView is showing exactly what it should.
I can't seem to find the error..
The main class:
package lassebjoerklund.easyfridge;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
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.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class BootActivity extends Activity {
//TODO Make get method for table with barcode.
//TODO Update postRequest so that it macthes the barcode to the database, and getting a json object. object -> toString
private ArrayList<Products> productsToDisplayInlist;
private String TAG = BootActivity.class.getSimpleName();
private String getDataurl = "http://XXX.XXX.XXX.XXX/selectAll.php";
private static String insertDataUrl = "http://XXX.XXX.XXX.XXX/insertAll.php";
private JsonArrayRequest jsonArrayRequest;
private RecyclerView.Adapter mAdapter;
private String jsonRespons = "";
private static RequestQueue rQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
//Layout
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_boot_layout);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.cardList);
recyclerView.setHasFixedSize(false);
recyclerView.setLayoutManager(linearLayoutManager);
//RequestQueue
rQueue = Volley.newRequestQueue(this);
productsToDisplayInlist = new ArrayList<>();
getRequest();
Log.d(TAG, productsToDisplayInlist.toString());
mAdapter = new ProductCardAdapter(productsToDisplayInlist);
recyclerView.setAdapter(mAdapter);
//Intent to switch to activity
//final Intent dispalyProductsIntent = new Intent(BootActivity.this, ProductViewController.class);
//final Intent scanBarcodeIntent = new Intent(BootActivity.this, BarcodeTracking.class);
//final ImageButton updateViewButton = (ImageButton) findViewById(R.id.bViewProducts);
/*updateViewButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(dispalyProductsIntent);
}
});*/
/* final ImageButton addNewEntry = (ImageButton) findViewById(R.id.addEntry);
addNewEntry.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
startActivity(scanBarcodeIntent);
}
});*/
}
#Override
protected void onResume() {
Log.d("onResume", "onResume");
/*Toast toast = Toast.makeText(this, "onResume", Toast.LENGTH_LONG);
toast.show();*/
super.onResume();
}
#Override
protected void onRestart() {
Log.d("onRestart", "onRestart");
/*Toast toast = Toast.makeText(this, "onRestart", Toast.LENGTH_SHORT);
toast.show();*/
super.onRestart();
}
#Override
protected void onStop() {
Log.d("onStop", "onStop");
// productsToDisplayInlist.clear();
super.onStop();
}
#Override
protected void onPause() {
Log.d("onPause", "onPause");
super.onPause();
}
//TODO make error msg if there is no connection.
public void getRequest() {
productsToDisplayInlist.clear();
jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, getDataurl, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//Log.d(TAG, response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject productToBuild = (JSONObject) response.get(i);
jsonRespons = productToBuild.toString();
String barcode = productToBuild.getString("code");
String name = productToBuild.getString("name");
String type = productToBuild.getString("type");
int id = productToBuild.optInt("id");
String rmDate = productToBuild.getString("rm_date");
String exDate = productToBuild.getString("ex_date");
String placementDate = productToBuild.getString("add_date");
Products product = new Products(barcode, name, placementDate, exDate, rmDate, type);
productsToDisplayInlist.add(product);
Log.d("Product", product.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Volly", "Error");
error.printStackTrace();
}
});
rQueue.add(jsonArrayRequest);
}
public static void postRequest(final Products product) {
try {
StringRequest stringRequest = new StringRequest(Request.Method.POST, insertDataUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
VolleyLog.d("onResponse", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Volley insertData", "ERROR");
Log.d("error: ", error.getCause().toString());
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> perameters = new HashMap<>();
perameters.put("barcode", product.getBarcode());
perameters.put("addDate", product.getDayOfadd());
perameters.put("exDate", product.getExDate());
return perameters;
}
};
rQueue.add(stringRequest);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here I init the layout and add the adapter for the RecycleView. The productsToDisplayInList is populated in the getRequest() method. But somehow, it's only periodic getting populated..
Adapter class:
package lassebjoerklund.easyfridge;
import android.graphics.Color;
import android.support.v7.widget.CardView;
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.Toast;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class ProductCardAdapter extends RecyclerView.Adapter<ProductHolder> {
private CardView cardView;
private List<Products> productses;
private Calendar c;
public ProductCardAdapter(ArrayList<Products> items) {
productses = items;
}
#Override
public int getItemCount() {
return productses.size();
}
#Override
public void onBindViewHolder(ProductHolder holder, int position) {
Products product = productses.get(position);
Date returnDate = Util.parseDateString(product.getExDate());
if (Util.getCurrentDate().after(returnDate)) {
cardView.setCardBackgroundColor(Color.parseColor("#FF000D"));
holder.cardName.setText(product.getName());
holder.cardAddDate.setText(product.getDayOfadd());
holder.cardExDate.setText(product.getExDate());
holder.cardType.setText(product.getType());
Log.d("Product Card", product.toString());
} else {
holder.cardName.setText(product.getName());
holder.cardAddDate.setText(product.getDayOfadd());
holder.cardExDate.setText(product.getExDate());
holder.cardType.setText(product.getType());
Log.d("Product Card", product.toString());
}
}
#Override
public ProductHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardlayout, parent, false);
cardView = new CardView(parent.getContext());
return new ProductHolder(itemView);
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
}
Holder Class:
package lassebjoerklund.easyfridge;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
public class ProductHolder extends RecyclerView.ViewHolder {
protected TextView cardName;
protected TextView cardAddDate;
protected TextView cardExDate;
protected TextView cardType;
public ProductHolder(View itemView) {
super(itemView);
cardName = (TextView) itemView.findViewById(R.id.cardName);
cardAddDate = (TextView) itemView.findViewById(R.id.cardAddDate);
cardExDate = (TextView) itemView.findViewById(R.id.cardExDate);
cardType = (TextView) itemView.findViewById(R.id.cardType);
}
}
I'm just doing some learning and can't see why this ArrayList is initialised but can't be used outside of method its populated within. Can anyone explain? Thanks in advance...
For example if I aske the ArrayList.size() within the method it shows that it has been initialised but elsewhere outside the method it won't.
package com.purewowstudio.animations;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
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.GsonBuilder;
import com.purewowstudio.animations.extras.CustomGrid;
import com.purewowstudio.animations.models.ActorArray;
import com.purewowstudio.animations.models.ActorObject;
import java.util.ArrayList;
public class ActorList extends ActionBarActivity {
String LOG_TAG = ActorList.class.getSimpleName();
private ArrayList<ActorObject> actorObjectArrayList;
ActorArray actorArray;
GridView actorGrid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actors_list);
getActors();
if (actorObjectArrayList != null) {
ActorObject[] actors = actorObjectArrayList.toArray(new ActorObject[actorObjectArrayList.size()]);
String actorsNames[] = new String[actorObjectArrayList.size()];
String actorsImages[] = new String[actorObjectArrayList.size()];
for (int i = 0; i < actorObjectArrayList.size(); i++) {
actorsNames[i] = actors[i].getName();
actorsImages[i] = actors[i].getImage();
}
CustomGrid adapter = new CustomGrid(ActorList.this, actorsNames, actorsImages);
actorGrid = (GridView) findViewById(R.id.grid);
actorGrid.setAdapter(adapter);
actorGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Toast.makeText(ActorList.this, "You Clicked at " + actorsNames[+position], Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.animation_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void getActors(){
String url ="http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors";
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
actorArray = new GsonBuilder().create().fromJson(response, ActorArray.class);
actorObjectArrayList = actorArray.getActors();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Log.v(LOG_TAG, "Volley Error");
}
});
queue.add(stringRequest);
}
}
The reason why you can't access the content with which you initialized the arraylist in other methods is simple. It is local data inside the scope of the OnCreate. You should define a constructor of your class and initialize the arraylist there. Then in your methods, you can add the data that you need to add. When you'll be looking for data within the arraylist, it will have everything that you're looking for.