I want to send the Id_student variable to MySQL but face to the following exception:
org.json.JSONException: Value 0 of type java.lang.Integer cannot be
converted to JSONArray
I have attached my code as following:
int id_student=123;
String GET_JSON_DATA_HTTP_URL ="http://pharamjo.96.lt/Select/ImageJsonData.php?";
String JSON_IMAGE_TITLE_NAME = "Id_student";
String JSON_IMAGE_URL = "Url";
JsonArrayRequest jsonArrayRequest ;
RequestQueue requestQueue ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
GetDataAdapter1 = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
recyclerViewlayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(recyclerViewlayoutManager);
JSON_DATA_WEB_CALL();
//show = (TextView)findViewById(R.id.show);
/*Intent intent = getIntent();
id_student = intent.getStringExtra("student");
//show.setText(id_student);*/
}
public void JSON_DATA_WEB_CALL(){
jsonArrayRequest = new JsonArrayRequest(GET_JSON_DATA_HTTP_URL + id_student ,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("Select", "onResponse");
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("********Select********",error.getMessage());
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array){
for(int i = 0; i<array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitleNamee(json.getString(JSON_IMAGE_TITLE_NAME));
GetDataAdapter2.setImageServerUrl(json.getString(JSON_IMAGE_URL));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(GetDataAdapter1, this);
recyclerView.setAdapter(recyclerViewadapter);
}
Would you please guide me to solve my problem?
Related
people so I have a valid URL with JSON data in it, I pull the data with volley but it's not working for some reason, when I change the URL it works. But I need to use this URL with this data in my project. I think the structure of the URL is the problem, but I don't know how to fix it, Please help. Thank you!
The URL I am using is https://zlatnakopacka.mk/api/TopOfferPreview_feed?source=zk
public class TestOne extends AppCompatActivity {
String url = "https://zlatnakopacka.mk/api/TopOfferPreview_feed?source=zk";
RecyclerView recyclerView;
PonudiAdapter adaptor;
ArrayList<Ponudi> ponudis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_one);
switchSve = findViewById(R.id.switch1);
recyclerView = findViewById(R.id.testRecycler);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adaptor = new PonudiAdapter(getApplicationContext());
recyclerView.setAdapter(adaptor);
ponudis = new ArrayList<>();
getData("1");
switchSve.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked == true) {
getData("sve");
} else {
getData("1");
}
}
});
private void getData(final String Sport) {
// final ProgressDialog progressDialog = new ProgressDialog(this);
// progressDialog.setMessage("Се вчитува...");
// progressDialog.show();
ponudis.clear();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
Ponudi ponudi = new Ponudi();
ponudi.setSh_sport_id(jsonObject.getString("sh_sport_id"));
ponudi.setTim1(jsonObject.getString("tim1"));
ponudi.setTim2(jsonObject.getString("tim2"));
ponudi.setLiga_header(jsonObject.getString("liga_header"));
ponudi.setDatum_vreme(jsonObject.getString("datum_vreme"));
ponudi.setKh1(jsonObject.getString("kh1"));
ponudi.setKhx(jsonObject.getString("khx"));
ponudi.setKh2(jsonObject.getString("kh2"));
ponudi.setKod(jsonObject.getString("broj"));
if (ponudi.getSh_sport_id().equals(Sport)) {
ponudis.add(ponudi);
} if (Sport.equals("sve")) {
ponudis.add(ponudi);
}
}
} catch (JSONException e) {
Toast.makeText(TestOne.this, "Json is not valid", Toast.LENGTH_SHORT).show();
}
adaptor.setData(ponudis);
adaptor.notifyDataSetChanged();
// progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// progressDialog.dismiss();
Toast.makeText(TestOne.this, "Error", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
}
In response you are getting below error.
"javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found."
I found some answers here is reference that will help you.
Trusting all certificates using HttpClient over HTTPS
Replace getData() Method
Write This method -
private void getData() {
// final ProgressDialog progressDialog = new ProgressDialog(this);
// progressDialog.setMessage("Се вчитува...");
// progressDialog.show();
ponudis.clear();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
Ponudi ponudi = new Ponudi();
ponudi.setSh_sport_id(jsonObject.getString("sh_sport_id"));
ponudi.setTim1(jsonObject.getString("tim1"));
ponudi.setTim2(jsonObject.getString("tim2"));
ponudi.setLiga_header(jsonObject.getString("liga_header"));
ponudi.setDatum_vreme(jsonObject.getString("datum_vreme"));
ponudi.setKh1(jsonObject.getString("kh1"));
ponudi.setKhx(jsonObject.getString("khx"));
ponudi.setKh2(jsonObject.getString("kh2"));
ponudi.setKod(jsonObject.getString("broj"));
if (ponudi.getSh_sport_id().equals("1")) {
ponudis.add(ponudi);
} else if(ponudi.getSh_sport_id().equals("sve")) {
ponudis.add(ponudi);
}
}
} catch (JSONException e) {
Toast.makeText(TestOne.this, "Json is not valid", Toast.LENGTH_SHORT).show();
}
adaptor.setData(ponudis);
adaptor.notifyDataSetChanged();
// progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// progressDialog.dismiss();
Toast.makeText(TestOne.this, "Error", Toast.LENGTH_SHORT).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
I am trying to get a JSON request from an API using volley but it didn't seem to work. I did try another dummy API and it works but not for this one. The one I am currently using has headers with key and value. Also, on checking the API on postman, I saw that the JSON format begins with '[' so I am not sure what to put for the JSONObject. Also, I am not sure if I added the header right. I am very new to android and would definitely appreciate it if someone could help me out.
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private ExampleAdapter mExampleAdapter;
private ArrayList<ExampleItem> mExampleList;
private RequestQueue mRequestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mExampleList = new ArrayList<>();
mRequestQueue = Volley.newRequestQueue(this);
parseJSON();
}
private void parseJSON() {
String url = "http://apidev.travelhouse.world/api/v1/packages";
JsonArrayRequest request = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject hit = response.getJSONObject(i);
String creatorName = hit.getString("holiday_name");
String imageUrl = hit.getString("primary_image");
String likeCount = hit.getString("package_price");
mExampleList.add(new ExampleItem(imageUrl, creatorName, likeCount));
}
mExampleAdapter = new ExampleAdapter(MainActivity.this, mExampleList);
mRecyclerView.setAdapter(mExampleAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Toast.makeText(MainActivity.this, "Failed to connect", Toast.LENGTH_LONG).show();
}
}) {
/** Passing some request headers* */
#Override
public Map getHeaders() throws AuthFailureError {
HashMap headers = new HashMap();
headers.put("Content-Type", "application/json");
headers.put("X-API-KEY", "CODEX#123");
return headers;
}
};
mRequestQueue.add(request);
}
Replace your JsonObjectRequest with:
JsonArrayRequest request = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
for (int i = 0; i < jsonArray.length(); i++) {....}
}
}
hi i have an app shows the online streamers from Twitch.tv and the data comes from request i send but i cant parse them this is my code
public ArrayList<Twitch> ParseTwitch(JSONArray object, Context context){
ArrayList<Twitch> chanels = new ArrayList<>();
try {
for (int i = 0;i<object.length();i++){
JSONObject streamObjct = object.getJSONObject(i);
JSONObject chanel = streamObjct.getJSONObject("channel");
JSONObject url= streamObjct.getJSONObject("preview");
final Twitch twitch = new Twitch();
twitch.setName(chanel.getString(CHANEL_NAME));
twitch.setStatus(chanel.getString(CHANEL_STATUS));
twitch.setGame(streamObjct.getString(GAME));
twitch.setLanguage(chanel.getString(BROADCASTER_LANGUAGE));
twitch.setViewrs(streamObjct.getInt(VIEWRS));
String imageUrl = url.getString("medium");
ImageRequest request =new ImageRequest(imageUrl, new Response.Listener<Bitmap>() {
#Override
public void onResponse(Bitmap response) {
twitch.setLogo(response);
}
}, 0, 0, null, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue quew = Volley.newRequestQueue(context);
quew.add(request);
chanels.add(twitch);
}
return chanels;
}catch (JSONException e){
e.printStackTrace();
}
return chanels;
}
and this my request
https://api.twitch.tv/kraken/search/streams?query=poker&client_id=gxdzx71jhztgyypn4kjemm1htovv1o
at least can anyone tell me should i work with sqlite Database or not?
where i called TwitchParcer
private void prepareData(String url, final ListView mListView) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray stream = response.getJSONArray("streams");
TwitchApiParser parser = new TwitchApiParser();
ArrayList items= parser.ParseTwitch(stream);
TwitchAdapter adapter = new TwitchAdapter(getContext(),
R.layout.activity_last_news_fragment,items);
mListView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), "Ridi Bro", Toast.LENGTH_SHORT).show();
}
});
RequestQueue quew = Volley.newRequestQueue(getActivity().getApplicationContext());
quew.add(request);
}
and this is new Error
Process: app.mma.introsliderproject, PID: 11542
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at app.mma.PokerInfo.twitch.TwitchAdapter.getView(TwitchAdapter.java:39)
i solve the problem this is the complete code
public class TwitchFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.twitch_main, container, false);
String url="http://192.168.1.101/mySite/Flowers/flowers2.json";
ListView mListView = (ListView) view.findViewById(R.id.twitch_last);
prepareData(url,mListView);
return view;
}
private void prepareData(String url, final ListView mListView) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray stream = response.getJSONArray("streams");
TwitchApiParser parser = new TwitchApiParser();
ArrayList items= parser.ParseTwitch(stream,getActivity().getApplicationContext());
TwitchAdapter adapter = new TwitchAdapter(getContext(),
R.layout.twitch,items);
mListView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), "Ridi Bro", Toast.LENGTH_SHORT).show();
}
});
RequestQueue quew = Volley.newRequestQueue(getActivity().getApplicationContext());
quew.add(request);
}
and the parser
public class TwitchApiParser {
private final String CHANEL_NAME="display_name";
private final String GAME="game";
private final String CHANEL_STATUS = "status";
private final String BROADCASTER_LANGUAGE = "broadcaster_language";
private final String VIEWRS = "viewers";
public ArrayList<Twitch> ParseTwitch(JSONArray object, Context context){
ArrayList<Twitch> chanels = new ArrayList<>();
try {
for (int i = 0;i<object.length();i++){
JSONObject streamObjct = object.getJSONObject(i);
JSONObject chanel = streamObjct.getJSONObject("channel");
JSONObject url= streamObjct.getJSONObject("preview");
final Twitch twitch = new Twitch();
twitch.setName(chanel.getString(CHANEL_NAME));
twitch.setStatus(chanel.getString(CHANEL_STATUS));
twitch.setGame(streamObjct.getString(GAME));
twitch.setLanguage(chanel.getString(BROADCASTER_LANGUAGE));
twitch.setViewrs(streamObjct.getInt(VIEWRS));
String imageUrl = url.getString("medium");
ImageRequest request =new ImageRequest(imageUrl, new Response.Listener<Bitmap>() {
#Override
public void onResponse(Bitmap response) {
twitch.setLogo(response);
}
}, 0, 0, null, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue quew = Volley.newRequestQueue(context);
quew.add(request);
chanels.add(twitch);
}
return chanels;
}catch (JSONException e){
e.printStackTrace();
}
return chanels;
}
I'm having a problem with Volley and the RecyclerView.
In the onCreate Method of my Activity, I call a Volley Request to get data from my server. I then pass it to my Adapter as a List.
The thing is that everything is happening so fast when the onCreate method has finished my Volley Request hasn't finished yet, so nothing is displayed on the screen, how can I avoid this?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity__services__worker);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Servicios");
final List services = new ArrayList();
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Method.GET, AppConfig.URL_GET_SERVICES_REQUIRED, new Response.Listener<String>(){
#Override
public void onResponse(String response){
try{
JSONArray jsonArray = new JSONArray(response);
for(int i=0; i<jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String tag_servicio = jsonObject.getString("contratista");
String servicio = jsonObject.getString("descipcion_del_problema");
String zona = jsonObject.getString("zona");
String money = jsonObject.getString("precio_min");
//Toast.makeText(Activity_Services_Worker.this, tag_servicio+servicio+zona+money, Toast.LENGTH_SHORT).show();
services.add(new Servicios_worker(tag_servicio, servicio, zona, money));
}
}catch (JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse (VolleyError error){
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(Activity_Services_Worker.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
requestQueue.add(stringRequest);
recycler = (RecyclerView) findViewById(R.id.servicesAsked_RecyclerView);
recycler.setHasFixedSize(true);
lManager = new LinearLayoutManager(this);
recycler.setLayoutManager(lManager);
adapter = new Adapter_services_required(services);
recycler.setAdapter(adapter);
}
In the add method, which I think is adding an element to the array of elements of the adapter, you should do notifyDatasetChanged() or you can do this:
...
final List services = new ArrayList();
;; CHANGED
recycler = (RecyclerView) findViewById(R.id.servicesAsked_RecyclerView);
recycler.setHasFixedSize(true);
lManager = new LinearLayoutManager(this);
recycler.setLayoutManager(lManager);
adapter = new Adapter_services_required(services);
recycler.setAdapter(adapter);
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Method.GET, AppConfig.URL_GET_SERVICES_REQUIRED, new Response.Listener<String>(){
#Override
public void onResponse(String response){
try{
JSONArray jsonArray = new JSONArray(response);
for(int i=0; i<jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
String tag_servicio = jsonObject.getString("contratista");
String servicio = jsonObject.getString("descipcion_del_problema");
String zona = jsonObject.getString("zona");
String money = jsonObject.getString("precio_min");
//Toast.makeText(Activity_Services_Worker.this, tag_servicio+servicio+zona+money, Toast.LENGTH_SHORT).show();
services.add(new Servicios_worker(tag_servicio, servicio, zona, money));
;; CHANGED
adapter.notifyDatasetChanged();
}
}catch (JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener(){
#Override
public void onErrorResponse (VolleyError error){
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(Activity_Services_Worker.this, error.getMessage(), Toast.LENGTH_LONG).show();
}
});
requestQueue.add(stringRequest);
see image click on first First Image ,get value on second second imageI want to get All item id in spinner when I clicked on recycler
view any selected item and get all item id get from recyclerview list.
My Code :
public class Assigned extends AppCompatActivity
{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.assign);
recyclerView = (RecyclerView) findViewById(R.id.cardList);
final LinearLayoutManager layoutManager = new LinearLayoutManager(context);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
model_joblists = new ArrayList<>();
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(context, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent intent = new Intent(getApplicationContext(), JobSubmission_First.class);
HashMap<String, String> selected_item = Item_List.get(position);
intent.putExtra("job_no",selected_item.get(JOB_NO));
intent.putExtra("job_description",selected_item.get(DESCRIPTION_NAME));
startActivity(intent);
}
})
);
getDataNew();
}
private void getDataNew()
{
String url = "http://10.54.103.8:4067/services/Webservices/joblisting";
HashMap<String, String> user = session.getUserDetails();
String token = user.get(SessionManager.KEY_TOKEN);
Log.e("token ", token);
final String role = user.get(SessionManager.KEY_ROLE);
Log.e("role", role);
String user_id = user.get(SessionManager.KEY_USERID);
Log.e("user_id", String.valueOf(user_id));
Map<String, String> params = new HashMap();
params.put(KEY_TOKEN, token);
params.put(KEY_ROLE, role);
params.put(KEY_ID, user_id);
JSONObject parameters = new JSONObject(params);
final ProgressDialog loading = ProgressDialog.show(this, "Loading Data", "Please wait...", false, false);
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url, parameters, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response)
{
try {
String req = response.getString("err-code");
if (0 == Integer.parseInt(req)) {
Log.e("response mila", response.toString());
ParseData(response);
loading.dismiss();
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
//TODO: handle failure
}
});
jsonRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT))
Volley.newRequestQueue(this).add(jsonRequest);
}
private void ParseData(JSONObject Object)
{
try {
JSONArray jsonArray = Object.getJSONArray("job_details");
for (int m = 0; m < jsonArray.length(); m++) {
Model_joblist model_joblist= new Model_joblist();
JSONObject jsonObject = jsonArray.getJSONObject(m);
HashMap<String, String> item = new HashMap<String, String>();
String job=jsonObject.getString("job_no");
String jobdes=jsonObject.getString("job_description");
item.put(JOB_NO, jsonObject.getString(JOB_NO));
item.put(DESCRIPTION_NAME,jsonObject.getString(DESCRIPTION_NAME));
Item_List.add(item);
jobdesnext.add(jsonObject.getString("job_description"));
jobno_spineer.add(jsonObject.getString("job_no"));
Log.e("spineer value", jobno_spineer.toString());
model_joblists.add(model_joblist);
}
String from[]={JOB_NO,DESCRIPTION_NAME};
int to[]={R.id.textSpinner,R.id.jobdescription};
spinnerAdapter=new SimpleAdapter(getApplicationContext(),Item_List,R.layout.assign,from,to);
} catch (JSONException e) {
e.printStackTrace();
}
ContactAdapter adapter2 = new ContactAdapter(model_joblists);
recyclerView.setAdapter(adapter2);
}
}