Android: Parsing JSON. No value for...? - arrays

I am trying to parse JSON data generated by an API.Here is the json I am trying to parse:
{
"response":{
"legislator":[
{
"#attributes":{
"cid":"N00033987",
"firstlast":"Doug LaMalfa",
"lastname":"LAMALFA",
"party":"R",
"office":"CA01",
"gender":"M",
"first_elected":"2012",
"exit_code":"0",
"comments":"",
"phone":"202-225-3076",
"fax":"530-534-7800",
"website":"http:\/\/lamalfa.house.gov",
"webform":"https:\/\/lamalfa.house.gov\/contact\/email-me",
"congress_office":"322 Cannon House Office Building",
"bioguide_id":"L000578",
"votesmart_id":"29713",
"feccandid":"H2CA02142",
"twitter_id":"RepLaMalfa",
"youtube_url":"https:\/\/youtube.com\/RepLaMalfa",
"facebook_id":"RepLaMalfa",
"birthdate":"1960-07-02"
}
The response json object inside of the entire response is throwing me off. I cant get to the legislator array. The logcat gives me this error:
How can I modify my method to get to the legislator json array?
Here is my parsing method:
private void getData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject responseObj = jsonObject.getJSONObject("response");
JSONArray array = responseObj.getJSONArray("legislator");
for(int i = 0; i < array.length(); i++){
JSONObject attributesObj = array.getJSONObject(i);
//create object
Legs leg = new Legs(attributesObj.getString("firstlast"),
attributesObj.getString("party"),
attributesObj.getString("office"),
attributesObj.getString("gender"),
attributesObj.getString("birthdate"),
attributesObj.getString("first_elected"),
attributesObj.getString("phone"),
attributesObj.getString("website"),
attributesObj.getString("congress_office"),
attributesObj.getString("twitter_id"),
attributesObj.getString("youtube_url"),
attributesObj.getString("facebook_id"));
legList.add(leg);
}
adapter = new LegRvAdapter(Legislators.this, legList);
myrv.setAdapter(adapter);
}catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("Volley", volleyError.toString());
progressDialog.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}

Related

JSONArray cannot be converted to JSONObject error when used as similar code

I get this error when I did the same this to my register method, I used this on my Login and it works well, but in register I get the error that the array cannot be converted to JSONObject, I am trying to put the array to convert it to JSONObject to send it to my PHP code for the database
This is my register method
private void registerUser() {
final String phone = phonenumber.getText().toString().trim();
final String lname = lastname.getText().toString().trim();
final String fname = fullname.getText().toString().trim();
final String mname = middlename.getText().toString().trim();
final String add = address.getText().toString().trim();
final String count = country.getText().toString().trim();
//first we will do the validations
if (TextUtils.isEmpty(lname)) {
lastname.setError("Please your Last Name");
lastname.requestFocus();
return;
}
if (TextUtils.isEmpty(fname)) {
fullname.setError("Please enter your First Name");
fullname.requestFocus();
return;
}
if (TextUtils.isEmpty(add)) {
address.setError("Please enter your Address");
fullname.requestFocus();
return;
}
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_REGISTER,
new Response.Listener<String>() {
#Override
public void onResponse(String Response) {
try {
//converting response to json object
JSONObject obj = new JSONObject(Response);
//if no error in response
if (!obj.getBoolean("error")) {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
//getting the user from the response
JSONObject userJson = obj.getJSONObject("user");
//creating a new user object
User user = new User(
userJson.getString("phone_number"),
userJson.getString("lastname"),
userJson.getString("fullname"),
userJson.getString("middleinitial"),
userJson.getString("country"),
userJson.getString("address")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
//starting the profile activity
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
} else {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("phone_number", phone);
params.put("lastname", lname);
params.put("fullname", fname);
params.put("middleinitial", mname);
params.put("country", count);
params.put("address",add);
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
this code got the error of JSON Array cannot be converted while my Login Code with the same format is working
this is my login code:
private void userLogin(){
//first getting the values
final String phonenumber = etNumber.getText().toString();
//validating inputs
if (TextUtils.isEmpty(phonenumber)) {
etNumber.setError("Please enter your Number");
etNumber.requestFocus();
return;
}
//if everything is fine
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting response to json object
JSONObject obj = new JSONObject(response);
//if no error in response
if (!obj.getBoolean("error")) {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
//getting the user from the response
JSONObject userJson = obj.getJSONObject("user");
//creating a new user object
User user = new User(
userJson.getString("phone_number"),
userJson.getString("lastname"),
userJson.getString("fullname"),
userJson.getString("middleinitial"),
userJson.getString("country"),
userJson.getString("address")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
//starting the profile activity
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
} else {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("phone_number", phonenumber);
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
and the error I got on my Logs is this:
W/System.err: org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:112)
at org.json.JSONObject.<init>(JSONObject.java:168)
at org.json.JSONObject.<init>(JSONObject.java:181)
at com.example.redwallet.Register$4.onResponse(Register.java:127)
W/System.err: at com.example.redwallet.Register$4.onResponse(Register.java:120)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:82)
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:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7562)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)

Error of JSONObject cannot be converted to JSONArray

I am not able to pass the data from API json to my textview respectively
I am getting "org.json.JSONObject cannot be converted to JSONArray" error
ERRORS :
W/System.err: org.json.JSONException: Value {"message":"accurate","cod":"200","count":1,"list":[{"id":1252948,"name":"Warangal","coord":{"lat":18,"lon":79.5833},"main":{"temp":315.66,"feels_like":314.6,"temp_min":315.66,"temp_max":315.66,"pressure":1002,"humidity":16,"sea_level":1002,"grnd_level":975},"dt":1590404957,"wind":{"speed":2.13,"deg":129},"sys":{"country":"IN"},"rain":null,"snow":null,"clouds":{"all":53},"weather":[{"id":803,"main":"Clouds","description":"broken clouds","icon":"04d"}]}]}
of type org.json.JSONObject cannot be converted to JSONArray
W/System.err: at org.json.JSON.typeMismatch(JSON.java:112)
This is my MainActivity code :
public class MainActivity extends AppCompatActivity {
TextView temp, sunraise, sunsets, wind, pressure, visibility, humidity;
EditText search;
ConstraintLayout constraintLayout;
ImageButton search_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
temp = findViewById(R.id.temp);
sunraise = findViewById(R.id.sunrise);
sunsets = findViewById(R.id.sunset);
wind = findViewById(R.id.wind);
pressure = findViewById(R.id.pressure);
visibility = findViewById(R.id.visibility);
humidity = findViewById(R.id.humidity);
search = findViewById(R.id.your_city);
constraintLayout = findViewById(R.id.constraintLayout);
search_btn = findViewById(R.id.search_btn);
search_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ConnectivityManager ConnectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
assert ConnectionManager != null;
NetworkInfo networkInfo = ConnectionManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
new WeatherData().execute();
} else {
Snackbar snackbar = Snackbar.make(constraintLayout, "check your Internet connection", Snackbar.LENGTH_LONG);
snackbar.show();
}
}
});
}
class WeatherData extends AsyncTask<String, Void, String> {
String City = search.getText().toString();
#Override
protected String doInBackground(String... strings) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://community-open-weather-map.p.rapidapi.com/find?type=link%252C%20accurate&units=imperial%252C%20metric&q=warangal")
.get()
.addHeader("x-rapidapi-host", "community-open-weather-map.p.rapidapi.com")
.addHeader("x-rapidapi-key", "a65ed4164bmshecc6a41b1453609p12d370jsn36dc92fffc6d")
.build();
try {
Response response = client.newCall(request).execute();
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
if (s != null) {
try {
JSONArray jsonObject = new JSONArray(s);
if (jsonObject.length() > 0) {
JSONArray list = jsonObject.getJSONArray(Integer.parseInt("list"));
JSONObject o = list.getJSONObject(Integer.parseInt("0"));
JSONObject main = o.getJSONObject("main");
String temperature = main.getString("temp");
String press = main.getString("pressure");
temp.setText(temperature);
pressure.setText(press);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
This is my JSON :
{
"message":"accurate",
"cod":"200","count":1,
"list":
[{
"id":1252948,
"name":"Warangal",
"coord":
{
"lat":18,
"lon":79.5833
},
"main":
{
"temp":317.1,
"feels_like":316.2,
"temp_min":317.1,
"temp_max":317.1,
"pressure":1003,
"humidity":15,
"sea_level":1003,
"grnd_level":976
},
"dt":1590397763,
"wind":
{
"speed":1.96,
"deg":117
},
"sys":
{
"country":"IN"
},
"rain":null,
"snow":null,
"clouds":{"all":36
},
"weather":
[{
"id":802,
"main":"Clouds",
"description":"scattered clouds",
"icon":"03d"
}]
}]
}
I am just testing to display the json output into my respective textview.After my code is succesfull i will functionalize the search field to get data from API.
Can anyone help me out from this error !
Thank you !
First check if its a json array or json object before assigning if (json instanceof JSONObject)
Any why are you parsing string to integer?

Getting a null Array from a method

I've created a method that shall return a two-dimensional Array, everything works perfectly as the array is being correctly filled in the method's try.
But once I display the array on onCreate(), it's returning null.
public class ListTickets extends AppCompatActivity {
public String[][] ticketTab ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_tickets);
ticketTab = new String[Integer.valueOf(nbTicket)][nbTicketTab];
DisplayArray(getTicketsHTTP());
}
private String[][] getTicketsHTTP() {
final JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, URL, null,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
try {
JSONArray Jdata = response.getJSONArray("data");
for (int i=0; i < Jdata.length(); i++) {
try {
JSONObject oneTicket = Jdata.getJSONObject(i);
titreTicket = oneTicket.getString("1");
slaTicket = oneTicket.getString("30");
dateDebutTicket = oneTicket.getString("15");
urgenceTicket = oneTicket.getString("10");
statutTicket = oneTicket.getString("12");
idTicket = oneTicket.getString("2");
} catch (JSONException e) {
Log.e("Err", e.getMessage());
}
ticketTab[i][0] = titreTicket;
ticketTab[i][1] = slaTicket;
ticketTab[i][2] = dateDebutTicket;
ticketTab[i][3] = urgenceText(urgenceTicket);
ticketTab[i][4] = calculTempsRestant(dateDebutTicket, slaTicket, dateEchanceTicket);
ticketTab[i][5] = String.valueOf(ticketEnretard);
ticketTab[i][6] = statutTicket;
ticketTab[i][7] = idTicket;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error.Response", error.toString());
}
}
){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("App-Token",FirstEverActivity.App_Token);
params.put("Session-Token",session_token);
return params;
}
};
// add it to the RequestQueue
queue.add(getRequest);
return ticketTab;
}
}
I declared ticketTab outside the onCreate because when I declare it inside the method, I cannot change it inside the try.
How can I return the array correctly?
In your onCreate you are using this line:
ticketTab = new String[Integer.valueOf(nbTicket)][nbTicketTab];
and those values, nbTicket and nbTicketTab are not declared anywhere in your code, maybe that's why they are returning null, you have to initialize them and asign values.

android app development-passing parameter to database

I am trying to connect my app to database on localhost server.I can connect to it ut the problem is how to pass the parameter from app to php script.for eg i want all names having age less than 10 so i will pass the parameter to php.below is my code for connecting to database.please provide good reference
/* */
enter code here
public class TestExternalDatabaseActivity extends Activity {
/** Called when the activity is first created. */
TextView resultView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.enableDefaults(); //STRICT MODE ENABLED
resultView = (TextView) findViewById(R.id.result);
getData();
}
public void getData(){
String result = "";
InputStream isr = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/tahseen0amin/php/getAllCustomers.php"); //YOUR PHP SCRIPT ADDRESS
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
resultView.setText("Couldnt connect to database");
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
s = s +
"Name : "+json.getString("FirstName")+" "+json.getString("LastName")+"\n"+
"Age : "+json.getInt("Age")+"\n"+
"Mobile Using : "+json.getString("Mobile")+"\n\n";
}
resultView.setText(s);
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data "+e.toString());
}
}
}

How do I update the UI from a HttpWebRequest?

In my Mainpage.xaml.cs file I have a function that creates an instance of another class and tries to download a webpage using a HttpWebRequest from that instance. The problem is, once I've managed to download the webpage I can't send it back to the main UI thread. I've tried using Deployment.Current.Dispatcher.BeginInvoke to send the webpage back to a TextBlock I have waiting, but when I try I get an error telling me that I can't access the TextBlock from the other class. Is there any way to pass data between two threads without using LocalStorage?
EDIT: code below:
MainPage:
private void button1_Click(object sender, RoutedEventArgs e)
{
Member m = new Member(name, id);
}
Member class:
public Member(String Member, String API)
{
APIKey = API;
MemberName = Member;
this.super = super;
DoSend(method, string, "", null);
}
public void DoSend(string method, string url, string body, string mimetype)
{
if (WebRequest.RegisterPrefix("https://",System.Net.Browser.WebRequestCreator.ClientHttp)) {
HttpWebRequest request = WebRequest.Create(makeURI(url)) as HttpWebRequest;
request.Method = method;
request.Headers["X-NFSN-Authentication"] = MakeAuthHeader(url,body);
if (body != "")
{
byte[] bodyData = Encoding.UTF8.GetBytes(body);
request.ContentType = mimetype;
//Stuff Should Happen Here
}
else
doStuff(request);
}
public void doStuff(HttpWebRequest httpReq)
{
httpReq.BeginGetResponse(r =>
{
var httpRequest = (HttpWebRequest)r.AsyncState;
var httpResponse = (HttpWebResponse)httpRequest.EndGetResponse(r);
using (var reader = new StreamReader(httpResponse.GetResponseStream()))
{
var response = reader.ReadToEnd();
ResponseBlock.Text = response; //Invalid cross-thread reference
}
}, httpReq);
}
MainPage:
customClass.DownloadPage((result) =>
{
textBlock.Text = result;
},
(exception) =>
{
MessageBox.Show(exception.Message);
});
CustomClass:
public void DownloadPage(Action<string> callback, Action<Exception> exception)
{
WebClient webClient = new WebClient();
webClient.DonwloadStringCompleted += (s, e) =>
{
if (e.Error == null)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
callback(e.Result);
});
}
else
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
exception(e.Error);
});
}
};
webClient.DonwloadStringAsync();
}

Resources