I'm trying to retrieve Json data into a spinner that's in an alertdialog , it only loads if the spinner in the same activity but if it's in an alertDialog it gives me this Error :
Attempt to invoke virtual method 'void android.widget.Spinner.setAdapter(android.widget.SpinnerAdapter)' on a null object reference
package exir.exir;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
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.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import exir.exir.Helpers.FormAdapter;
import exir.exir.Helpers.PatientsAdapter;
import exir.exir.Helpers.PricrMAdapter;
import exir.exir.Helpers.RequestHandler;
import exir.exir.Helpers.SharedPrefManager;
import exir.exir.Rertofit.MyLabAPI;
import exir.exir.Utils.Constants;
import exir.exir.model.Form;
import exir.exir.model.PMenus;
import exir.exir.model.PriceM;
import exir.exir.model.RPatient;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import static android.R.layout.simple_spinner_item;
public class AddPatient extends AppCompatActivity {
private EditText patientname, gender , age , agetype , tel ,
phone , total , notes , testno , testprice , testnotes , testname1 , testno1 , testprice1 , testnotes1 ;
private Button add ;
private String URLstring = "https://demonuts.com/Demonuts/JsonTest/Tennis/json_parsing.php";
String labId , labpriceMenuNO ;
private static ProgressDialog mProgressDialog;
private ArrayList<PMenus> goodModelArrayList;
private ArrayList<String> names = new ArrayList<String>();
private Spinner PmSpinner;
MyLabAPI myLabAPI ;
CompositeDisposable compositeDisposable = new CompositeDisposable();
List<PriceM> pricemenilist;
ArrayAdapter<String> adapter;
ListView FormList ;
EditText editThen , edtSdt;
Button btn_sua , btn_xoa , btn_then ;
ArrayList<Form> formArrayList ;
FormAdapter formAdapter;
FloatingActionButton newTest ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_patient);
testno = (EditText)findViewById(R.id.testno);
testprice = (EditText)findViewById(R.id.testprice);
testnotes = (EditText)findViewById(R.id.testnotes);
newTest = (FloatingActionButton)findViewById(R.id.
newTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showNewTestDialog();
}
});
myLabAPI = Constants.getAPI();
add =(Button)findViewById(R.id.addPatient);
}
private void showNewTestDialog() {
AlertDialog.Builder alertDialog = new
AlertDialog.Builder(AddPatient.this);
alertDialog.setTitle("Add New Test ");
alertDialog.setMessage("PLease fill the info ");
LayoutInflater inflater = this.getLayoutInflater();
View formLayout = inflater.inflate(R.layout.newtest_layout, null);
editThen = formLayout.findViewById(R.id.FName);
edtSdt = formLayout.findViewById(R.id.FPrice);
goodModelArrayList = new ArrayList<>();
PmSpinner = (Spinner)findViewById(R.id.testname);
PmSpinner.setAdapter(adapter);
PmSpinner.setOnItemSelectedListener(new
AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int
position, long id) {
String item = parent.getItemAtPosition(position).toString() ;
String testum = goodModelArrayList.get(position).getCity() ;
String price = goodModelArrayList.get(position).getCountry() ;
testnotes.setText(item);
testno.setText(testum);
testprice.setText(price);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
retrieveJSON();
alertDialog.setView(formLayout);
alertDialog.setIcon(R.drawable.ic_shopping_cart_black_24dp);
alertDialog.setPositiveButton("YES", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
//some code
}
});
alertDialog.setNegativeButton("No", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
alertDialog.show();
}
private void retrieveJSON() {
StringRequest stringRequest = new StringRequest(
Request.Method.GET,
URLstring,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("strrrrr", ">>" + response);
try {
JSONObject obj = new JSONObject(response);
goodModelArrayList = new ArrayList<>();
JSONArray dataArray = obj.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
PMenus playerModel = new PMenus();
JSONObject dataobj =
dataArray.getJSONObject(i);
playerModel.setName(dataobj.getString("name"));
playerModel.setCountry(dataobj.getString("country"));
playerModel.setCity(dataobj.getString("city"));
playerModel.setImgURL(dataobj.getString("imgURL"));
goodModelArrayList.add(playerModel);
}
for (int i = 0; i < goodModelArrayList.size();
i++){
names.add(goodModelArrayList.get(i).getName().toString());
}
ArrayAdapter<String> spinnerArrayAdapter = new
ArrayAdapter<String>(AddPatient.this, simple_spinner_item, names);
spinnerArrayAdapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item); // The drop down view
PmSpinner.setAdapter(spinnerArrayAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
// request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Try this.....
JSONObject c = JSONfunctions.getJSONfromURL("http://192.168.1.104/OnlineTicketBooking/book_now1.php?movieid='72'");
try {
JSONArray jarray = c.getJSONArray("offer_detail");
ArrayList<String> xyz= new ArrayList<String>();
for(int i = 0; i < jarray.length(); i++){
JSONArray timeArray = jarray.getJSONObject(i).getJSONArray("showtime");
for(int j = 0; j < timeArray .length(); j++){
xyz.add(timeArray .getString(j));
Log.d("get value",timeArray .getString(j));`enter code here`
}
}
Related
package com.joshbradley.pokemonapp.activities;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
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.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.joshbradley.pokemonapp.R;
import com.joshbradley.pokemonapp.adapters.Adapter;
import com.joshbradley.pokemonapp.helperclass.HelperClass;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class HomeScreen extends AppCompatActivity {
//VARIABLES
RecyclerView recyclerView;
List<HelperClass> helperClasses;
Adapter adapter;
private static String JSON_URL_TEST = "https://pokeapi.co/api/v2/pokemon?limit=151";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
//RECYCLER AND VIEW
recyclerView = findViewById(R.id.home_screen_recycler);
helperClasses = new ArrayList<>();
//CALLING EXTRACT DATA METHOD
extractData();
}
//EXTRACT DATA & REQUESTS
private void extractData() {
RequestQueue queue = Volley.newRequestQueue(this);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, "https://pokeapi.co/api/v2/pokemon?limit=151", null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++){
try {
JSONObject jsonObject = response.getJSONObject(i);
HelperClass helperClass = new HelperClass();
helperClass.setName(jsonObject.getString("name"));
helperClass.setImageUrl(jsonObject.getString("url"));
helperClasses.add(helperClass);
} catch (JSONException e) {
e.printStackTrace();
}
}
//ADAPTER AND LAYOUT MANAGER
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
adapter = new Adapter(getApplicationContext(), helperClasses);
recyclerView.setAdapter(adapter);
}
// ERROR RESPONSE
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
queue.add(jsonArrayRequest);
}
}
// MY ERROR
com.android.volley.ParseError: org.json.JSONException: Value {"count":1154,"next":"https:\/\/pokeapi.co\/api\/v2\/pokemon?offset=151&limit=151","previous":null,"results":[{"name":"bulbasaur","url":"https:\/\/pokeapi.co\/api\/v2\/pokemon\/1\/"},{"name":"ivysaur","url":"https:\/\/pokeapi.co\/api\/v2\/pokemon\/2\/"},{"name":"venusaur","url":"https:\/\/pokeapi.co\/api\/v2\/pokemon\/3\/"},
In your extractData() method you have the following which implies that you are expecting the service response to be a JSONArray:
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, ...
If you look at the body of the Exception you will see that the service is returning an object (which contains an array).
{ "count":1154
, "next":"https:\/\/pokeapi.co\/api\/v2\/pokemon?offset=151&limit=151"
, "previous":null
, "results":[ ... some array of values]
... you cut it off so there may be more fields ...
}
As such, it looks like you should accept a JSONObject and then extract the value associated with the results key. I'm not sure on the syntax but probably something like...
JsonObjectRequest request = new JsonObjectRequest(...
#Override
public void onResponse(JSONObject response) {
JSONArray results = response.getJSONArray("results");
....
I have created a project in which I am using spinner.
In spinner I am setting data fetched from MySql database. The data is being fetched properly as I can get the whole in the dropdown.
The problem is that spinner is not showing the selected value in the text area.
When I tested it with another arraylist of strings which was created in the program it was working.
I don't know why it is not working properly with the data fetched from database.
Kindly help me if you know the solution.
The java file is here when I used the data from MySql database
package com.help.adminpasskart;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
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 addSubCategory extends AppCompatActivity {
ImageView categoryImageView , categoryImageBtn;
TextView categoryNameView ;
Button confirmBtn;
String categoryimg;
Spinner genderDrop , categoryDrop;
ArrayList<String> genders = new ArrayList<>();
ArrayList<String> words = new ArrayList<>();
private final String url = "http://passkart.online/Z_addCategory.php";
private final String url2 = "http://passkart.online/Z_getGender.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_sub_category);
categoryImageView = findViewById(R.id.addcategoryimageView);
categoryImageBtn = findViewById(R.id.addcategoryimagebtn);
categoryNameView = findViewById(R.id.addcategorynameView);
confirmBtn = findViewById(R.id.addCategoryConfirmBtn);
genderDrop = findViewById(R.id.genderDropDown);
categoryDrop = findViewById(R.id.categoryDropDown);
getGenders();
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(addSubCategory.this,
R.layout.droptextlayout,genders);
myAdapter.notifyDataSetChanged();
genderDrop.setAdapter(myAdapter);
genderDrop.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long
id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "Selected: " + item,
Toast.LENGTH_LONG).show();
genderDrop.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void getGenders(){
StringRequest request = new StringRequest(Request.Method.POST, url2, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject Jobject = new
JSONObject(response.substring(response.indexOf("{"), response.lastIndexOf("}") + 1));
String success = Jobject.getString("success");
JSONArray Jarray = Jobject.getJSONArray("datas");
if(success.equals("1")) {
for (int i = 0; i < Jarray.length(); i++) {
JSONObject object = Jarray.getJSONObject(i);
String name = object.getString("name");
genders.add(name);
}
}
} catch (JSONException jsonException) {
jsonException.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(addSubCategory.this);
queue.add(request);
};
}
The java file is here when I used the arraylist created in the program.In this code the spinner is working fine
package com.help.adminpasskart;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
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 addSubCategory extends AppCompatActivity {
ImageView categoryImageView , categoryImageBtn;
TextView categoryNameView ;
Button confirmBtn;
String categoryimg;
Spinner genderDrop , categoryDrop;
ArrayList<String> genders = new ArrayList<>();
ArrayList<String> words = new ArrayList<>();
private final String url = "http://passkart.online/Z_addCategory.php";
private final String url2 = "http://passkart.online/Z_getGender.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_sub_category);
categoryImageView = findViewById(R.id.addcategoryimageView);
categoryImageBtn = findViewById(R.id.addcategoryimagebtn);
categoryNameView = findViewById(R.id.addcategorynameView);
confirmBtn = findViewById(R.id.addCategoryConfirmBtn);
genderDrop = findViewById(R.id.genderDropDown);
categoryDrop = findViewById(R.id.categoryDropDown);
getGenders();
words.add("word1");
words.add("word2");
words.add("word3");
words.add("word4");
words.add("word5");
words.add("word6");
words.add("word7");
words.add("word8");
words.add("word9");
words.add("word10");
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(addSubCategory.this,
R.layout.droptextlayout,words);
myAdapter.notifyDataSetChanged();
genderDrop.setAdapter(myAdapter);
genderDrop.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long
id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "Selected: " + item,
Toast.LENGTH_LONG).show();
genderDrop.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void getGenders(){
StringRequest request = new StringRequest(Request.Method.POST, url2, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject Jobject = new
JSONObject(response.substring(response.indexOf("{"), response.lastIndexOf("}") + 1));
String success = Jobject.getString("success");
JSONArray Jarray = Jobject.getJSONArray("datas");
if(success.equals("1")) {
for (int i = 0; i < Jarray.length(); i++) {
JSONObject object = Jarray.getJSONObject(i);
String name = object.getString("name");
genders.add(name);
}
}
} catch (JSONException jsonException) {
jsonException.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(addSubCategory.this);
queue.add(request);
};
}
MySql file is here
<?php
include "config.php";
$sql="SELECT * FROM `$db`.`genderCategory`";
$result=mysqli_query($conn,$sql);
$categories['datas'] = array();
if(mysqli_num_rows($result)>0){
while($row=mysqli_fetch_array($result)){
$data['id']=$row['0'];
$data['name']= $row['1'];
$data['image']=$row['2'];
array_push($categories['datas'],$data);
}
$categories['success']='1';
echo json_encode($categories);
mysqli_close($conn);
}else{
echo "No gender added";
}
?>
Finally , I have solved it by myself
The problem was that the method getGenders() was not getting the arrayAdapter
So , I defined it inside the method and booyah !! My problem got solved .
public class addSubCategory extends AppCompatActivity {
ImageView categoryImageView , categoryImageBtn;
TextView categoryNameView ;
Button confirmBtn;
Spinner genderDrop , categoryDrop;
ArrayList<String> genders = new ArrayList<>();
ArrayAdapter<String> myAdapter;
private final String url2 = "http://passkart.online/Z_getGender.php";
String gender ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_sub_category);
categoryImageView = findViewById(R.id.addcategoryimageView);
categoryImageBtn = findViewById(R.id.addcategoryimagebtn);
categoryNameView = findViewById(R.id.addcategorynameView);
confirmBtn = findViewById(R.id.addCategoryConfirmBtn);
genderDrop = findViewById(R.id.genderDropDown);
categoryDrop = findViewById(R.id.categoryDropDown);
getGenders();
genderDrop.setOnItemSelectedListener(new
AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int
position, long id) {
myAdapter.notifyDataSetChanged();
String item = parent.getItemAtPosition(position).toString();
genderDrop.setSelection(position);
gender = item;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void getGenders(){
StringRequest request = new StringRequest(Request.Method.POST, url2,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject Jobject = new
JSONObject(response.substring(response.indexOf("{"),
response.lastIndexOf("}") + 1));
String success = Jobject.getString("success");
JSONArray Jarray = Jobject.getJSONArray("datas");
if(success.equals("1")) {
for (int i = 0; i < Jarray.length(); i++) {
JSONObject object = Jarray.getJSONObject(i);
String name = object.getString("name");
genders.add(name);
}
//Array adapter is defined here ..........
myAdapter = new ArrayAdapter<String> (addSubCategory.this, R.layout.droptextlayout,genders);
myAdapter.notifyDataSetChanged();
genderDrop.setAdapter(myAdapter);
}
} catch (JSONException jsonException) {
jsonException.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(addSubCategory.this);
queue.add(request);
};
}
I am posting this answer for those who are still dealing with this error.
This is my code for getting the data from JSON, it will contain only one row,
but it will give output for only "pro_name" for left of the values it will give just dots(......).
package com.example.sh_enterprises;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
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.View;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
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.List;
public class Detailes extends AppCompatActivity {
//this is the JSON Data URL
//make sure you are using the correct ip else it will not work
public static String URL_PRODUCTS, pass1,pass2 ;
public static String ptopic,psubcode;
private static ProgressDialog progressDialog;
//a list to store all the products
List<pro_data> productList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailes);
Intent i = getIntent();
pass1 = i.getStringExtra("pro_id");
//Toast.makeText(this,"HI THIS IS "+pass,Toast.LENGTH_SHORT).show();
//URL_PRODUCTS = "https://premnathindia.000webhostapp.com/Api.php?p1="+pass;
URL_PRODUCTS = "http://192.168.225.25/prem/Api.php?p1="+pass1+"&p2=det";
Toast.makeText(this, URL_PRODUCTS, Toast.LENGTH_SHORT).show();
productList = new ArrayList<>();
//this method will fetch and parse json
//to display it in recyclerview
loadProducts();
}
private void loadProducts() {
prefConfig product = new prefConfig(this);
String str = product.read_ret_id();
Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Please wait...");
progressDialog.show();
/*
* Creating a String Request
* The request type is GET defined by first parameter
* The URL is defined in the second parameter
* Then we have a Response Listener and a Error Listener
* In response listener we will get the JSON response as a String
* */
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
//traversing through all the object
for (int i = 0; i < 1; i++) {
//getting product object from json array
JSONObject product = array.getJSONObject(i);
product.getString("pro_id");
String st;
TextView a = findViewById(R.id.pro_name);
TextView b = findViewById(R.id.weight);
TextView c = findViewById(R.id.base_amount);
TextView d = findViewById(R.id.mass_amonut);
TextView e = findViewById(R.id.brand);
TextView f = findViewById(R.id.catogery);
String st1 = product.getString("pro_name");
a.setText(st1);
st = product.getString("weight");
b.setText(st);
st = product.getString("total_amount");
d.setText(st);
//st = product.getString("pro_img_url");
st = product.getString("base_amount");
c.setText(st);
//st = product.getString("disc");
st = product.getString("brands");
e.setText(st);
st = product.getString("categories");
f.setText(st);
}
progressDialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
public void downme_ooi(View view) {
String pro_id = ((TextView) view).getText().toString();
Intent i = new Intent(this,Detailes.class);
i.putExtra("pro_id",pro_id);
startActivity(i);
}
public void go_back(View view) {
super.onBackPressed();
}
}
Sorry I made the Mistake that in TextView I put the text as password .
I want to display JSON data in textView and i do that but the problem is when i create a separate class for lood JSON data and Store into A ArrayList, it doesn"t work.
Here is my code please help me what i can do to solve that problem.
My inner class code
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.example.mdashikurrahman.transactions.AppController;
import com.example.mdashikurrahman.transactions.HouseOrPerson;
import com.example.mdashikurrahman.transactions.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class InsertActivity extends Activity {
ArrayList<HouseOrPerson> arrayList= new ArrayList<>();
// json array response url
private String urlJsonArry = "http://testgarciaplumbing.3eeweb.com/ashik/select.php";
private Button btnMakeArrayRequest;
private TextView txtResponse;
// temporary string to show the parsed response
private String jsonResponse="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
btnMakeArrayRequest = (Button) findViewById(R.id.btnArrayRequest);
txtResponse = (TextView) findViewById(R.id.txtResponse);
btnMakeArrayRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
makeJsonArrayRequest();
}
});
}
/**
* Method to make json array request where response starts with [
* */
private void makeJsonArrayRequest() {
JsonArrayRequest req = new JsonArrayRequest(Request.Method.POST, urlJsonArry, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
HouseOrPerson houseOrPerson =new HouseOrPerson(person.getInt("house_id"),
person.getString("house_name"), person.getInt("balance"));
arrayList.add(houseOrPerson);
}
for (int x=0; x<arrayList.size(); x++){
jsonResponse +=Integer.toString(arrayList.get(x).getId())
+ arrayList.get(x).getName()
+ Integer.toString(arrayList.get(x).getBalance())+ "\n\n";
}
txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
}
Separate class code
BackgroundTask
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by MD ASHIKUR RAHMAN on 9/24/2016.
*/
public class BackgroundTask {
ArrayList<HouseOrPerson> arrayList= new ArrayList<>();
// json array response url
private String urlJsonArry = "http://testgarciaplumbing.3eeweb.com/ashik/select.php";
/**
* Method that return a arraylist which made by jsonArray
* */
public ArrayList<HouseOrPerson> makeJsonArrayRequest() {
JsonArrayRequest req = new JsonArrayRequest(Request.Method.POST, urlJsonArry, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
HouseOrPerson houseOrPerson =new HouseOrPerson(person.getInt("house_id"),
person.getString("house_name"), person.getInt("balance"));
arrayList.add(houseOrPerson);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
return arrayList;
}
}
InsertActivity class where i create a object ob BackGround class and call makeJsonArrayRequest method
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.example.mdashikurrahman.transactions.BackgroundTask;
import com.example.mdashikurrahman.transactions.HouseOrPerson;
import com.example.mdashikurrahman.transactions.R;
import java.util.ArrayList;
public class InsertActivity extends Activity {
ArrayList<HouseOrPerson> arrayList= new ArrayList<>();
private Button btnMakeArrayRequest;
private TextView txtResponse;
// temporary string to show the parsed response
private String jsonResponse="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
btnMakeArrayRequest = (Button) findViewById(R.id.btnArrayRequest);
txtResponse = (TextView) findViewById(R.id.txtResponse);
btnMakeArrayRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BackgroundTask bg = new BackgroundTask();
arrayList=bg.makeJsonArrayRequest();
for (int x=0; x<arrayList.size(); x++){
jsonResponse +=Integer.toString(arrayList.get(x).getId())
+ arrayList.get(x).getName()
+ Integer.toString(arrayList.get(x).getBalance())+ "\n\n";
}
txtResponse.setText(jsonResponse);
}
});
}
}
Arent you missing a constructor in your BackgroundTask?
Try putting System.out.println(arrayList.size()) before you return it in your BackgroundTask. What is the size of it?
Can anyone shed some light on this for me? I'm buiding this app for my final project that's due on Friday. Head. is. FRIED.
Getting this error on build
C:\Users\Gary\AndroidStudioProjects\NatureAll.v2\app\src\main\java\com\example\gary\natureallv2\SearchAnimalActivity.java:58: error: incompatible types: int cannot be converted to String
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(POST,
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error
It's telling me int can't be converted to string but I can't see where the int is. Here's my code:
package com.example.gary.natureallv2;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
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;
/**
* Created by Gary on 12/09/2016.Go Me
*/
public class SearchAnimalActivity extends AppCompatActivity{
EditText etSearchName;
Button btnSearch;
RequestQueue requestQueue;
String showUrl = "http://192.168.1.10/myDocs/mainProject/search_animal_and.php";
// String showUrl = "http://192.168.1.10/tutorial/showStudents.php";
TextView tvName;
TextView tvLatinName;
TextView tvDescription;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_animal_activity);
etSearchName = (EditText) findViewById(R.id.etSearchName);
tvName = (TextView) findViewById(R.id.tvName);
tvLatinName = (TextView) findViewById(R.id.tvLatinName);
tvDescription = (TextView) findViewById(R.id.tvDescription);
btnSearch = (Button) findViewById(R.id.btnSearch);
requestQueue = Volley.newRequestQueue(getApplicationContext());
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// System.out.println("ww");
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
showUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response.toString());
try {
JSONArray animals = response.getJSONArray("animals");
for (int i = 0; i < animals.length(); i++) {
JSONObject animal = animals.getJSONObject(i);
//Change here for different string names
String name = animal.getString("name");
String latinName = animal.getString("latinName");
String description = animal.getString("description");
tvName.append(name);
tvLatinName.append(latinName);
tvDescription.append(description);
}
//result.append("===\n");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.append(error.getMessage());
}
});
requestQueue.add(jsonObjectRequest);
}
});
}
}
Many thanks in advance
tvName.append(name);
tvLatinName.append(latinName);
tvDescription.append(description);
You are trying to append a string to a View which has a value of its id (int). This wont work. you should instead call a .setText() on your view and set the text to its current value plus what you want to append.