JSON error retrieving data from database, after registration - android

I am trying to get some data from a databse using JSON, but debugging the app showed me that Value null at ID_UTILIZ of type org.json.JSONObject$1 cannot be converted to int . I have checked the database and the ID_UTILIZ column is set as Int . This activity is used for registering, and also storing the data for SharedPreferences, so I am using also a User class, but I have also set the Id at int there too. I cannot see what I am doing wrong
code:
class RegisterUser extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
//creating request handler object
RequestHandler requestHandler = new RequestHandler();
//creating request parameters
HashMap<String, String> params = new HashMap<>();
params.put("nume", Nume);
params.put("email", Email);
params.put("Parola", Parola_cont);
params.put("prenume", Prenume);
params.put("telefon", Telefon);
params.put("departament", spinner);
//returing the response
return requestHandler.sendPostRequest(URLs.URL_REGISTER, params);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//displaying the progress bar while user registers on the server
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//hiding the progressbar after completion
try {
//converting response to json object
JSONObject obj = new JSONObject(s);
//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("Nume"),
userJson.getString("Prenume"),
userJson.getString("Adresa_mail"),
userJson.getString("Numar_telefon"),
userJson.getString("Parola"),
userJson.getInt("ID_UTILIZ"),
userJson.getString("Departament")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
finish();
startActivity(new Intent(getApplicationContext(), Home.class));
} else {
Toast.makeText(getApplicationContext(), "Some error occurred", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
//executing the async task
RegisterUser ru = new RegisterUser();
ru.execute();
}
php:
case 'inregistrare':
if(isTheseParametersAvailable(array('nume','email','Parola','prenume', 'telefon', 'departament'))){
$prenume = $_POST["prenume"];
$nume =$_POST["nume"];
$email =$_POST["email"];
$telefon =$_POST["telefon"];
$parola =md5($_POST["Parola"]);
$tip = 2;
$departament=$_POST["departament"];
$stmt = $conn->prepare("SELECT ID_UTILIZ FROM informatii_persoane WHERE Adresa_mail = ? OR Numar_telefon = ?");
$stmt->bind_param("ss", $email, $telefon);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows > 0){
$response['error'] = true;
$response['message'] = 'Utilizator existent';
$stmt->close();
}else{
$stmt = $conn->prepare("INSERT INTO informatii_persoane (Nume, Prenume, Adresa_mail, Numar_telefon, Parola, Tip_utilizator, Departament) VALUES (?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssis", $nume, $prenume, $email, $telefon, $parola, $tip, $departament);
if($stmt->execute()){
$stmt = $conn->prepare("SELECT ID_UTILIZ, Nume, Prenume, Adresa_mail, Numar_telefon, Parola, Departament FROM informatii_persoane WHERE Adresa_mail = ?");
$stmt->bind_param("s",$Adresa_mail);
$stmt->execute();
$stmt->bind_result($id, $nume, $prenume, $email, $telefon, $parola, $departament);
$stmt->fetch();
$user = array(
'Nume'=>$nume,
'Prenume'=>$prenume,
'Adresa_mail'=>$email,
'Numar_telefon'=>$telefon,
'Parola'=>$parola,
'ID_UTILIZ'=>$id,
'Departament'=>$departament
);
$stmt->close();
$response['error'] = false;
$response['message'] = 'Utilizator inregistrat cu success';
$response['user'] = $user;
}
}
}else{
$response['error'] = true;
$response['message'] = 'A aparut o eroare';
}
break;
The registering process it's working, I have all the data stored in database and I can log in later, but because of the error mentioned above, the code stops and:
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
finish();
startActivity(new Intent(getApplicationContext(), Home.class));
doesn't start the Home.class activity so my app stays on the same window. I have tried to search for other questions posted before, but none had a solution that worked. I think I am missing something, but I cannot see what. Thanks!

You can't not convert null to int. So, you have to check first your specific value is not null.
Try like this
int id_utiliz = -1; // set default value
// check ID_UTILIZ is not null and then get value.
if(!userJson.isNull("ID_UTILIZ")) {
id_utiliz = userJson.getInt("ID_UTILIZ");
}
//creating a new user object
User user = new User(
userJson.getString("Nume"),
userJson.getString("Prenume"),
userJson.getString("Adresa_mail"),
userJson.getString("Numar_telefon"),
userJson.getString("Parola"),
id_utiliz,
userJson.getString("Departament")
);
And Use finish() below the startActivity(...) like the following.
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
startActivity(new Intent(getApplicationContext(), Home.class));
finish(); // use this statement here.

You should make sure that ID_UTILIZ has any value defined, it should not be null. OR you can simply assign a default value to ID_UTILIZ in your table.

int primitive type doesn't accept null values, you can use the Integer wrapper class which can have a value of null, usually when serializing JSON object from network call i use wrapper class not primitives.
also use responseJsonObject.isNull(ID_UTILIZ) to check if object has no mapping for ID_UTILIZ or if it has a mapping whose value is NULL.

Related

Handling Volley when no key exists

I have implemented Volley and Recycler view to parse and display a list of few items from a simple JSON file.
There are at times when a key doesnot exists in an object but may appear in other object. That key is already defined using object.getInt("someKey").
As soon as Volley starts parsing the object with the missing key, it breaks out of the for loop (objects are stored in array) and catches the JSONException e, which is exactly what the app is supposed to do in case of a missing key.
However, I would like to prevent this behavior and use a placeholder value for that missing key of that particular object, so that the array list gets successfully buildup and recyclerview gets filled thereby application starts working normally.
What logic can I use in order to achieve this behavior?
Thank you!
private void parseJSON() {
String url = "https://example.com/index.json";
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject object = response.getJSONObject(i);
String title = object.getString("subject");
String description = object.getString("message");
String imageUrl = object.getString("thumb");
Integer threadId = object.getInt("threadId");
mList.add(new Item( title, description, threadId));
}
mItemAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
In the above code, threadId is the key, which may or maynot appear in many objects of the JSON.
You can check firstly if your key exists on object
try {
for (int i = 0; i < response.length(); i++) {
JSONObject object = response.getJSONObject(i);
String title = object.getString("subject");
String description = object.getString("message");
String imageUrl = object.getString("thumb");
Integer threadId;
if(object.toString().contain("threadId"){
threadId = object.getInt("threadId");
}else{
threadId = 0;
}
mList.add(new Item( title, description, threadId));
}
mItemAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
If i understood well your Question , here what you need to do , if you are not sure if this key exists use the following
jsonObject.optBoolean("yourKey");
jsonObject.optInt("yourKey");
jsonObject.optString("yourKey");
jsonObject.optLong("yourKey");
jsonObject.optDouble("yourKey");
jsonObject.optJSONArray("yourKey");
this will make sure jsonObject will ignore that key if it doesn't exist.
object.getInt("someKey") is to get value from "somekey".if somekey is not appeared it shows JSONException. Instead of this object.optInt("someKey"). It will get value from "somekey" if it appears, otherwise it skipped. This is simple solution. Thanks

Why do I get an empty response when my android app calls my API on my server?

I have android application that called information and show it as a list.
I have a spinner when you choose the date from the spinner you get the information related to that date.
In the app first load it calls automatically today information.
this is the code I use in my main activity to create my spinner and fill it with elements and handle the clicks on each item:
// Spinner element
spinner = (Spinner) v.findViewById(R.id.spinner);
// Spinner click listener
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// On selecting a spinner item
//String item = parent.getItemAtPosition(position).toString();
switch(position){
case 3:
if (JsonUtils.isNetworkAvailable(getActivity())) {
list.clear();
new MyTask().execute(Config.SERVER_URL + "/banko_api.php?d_o=-1");
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.failed_connect_network), Toast.LENGTH_SHORT).show();
}
break;
case 4:
if (JsonUtils.isNetworkAvailable(getActivity())) {
list.clear();
new MyTask().execute(Config.SERVER_URL + "/banko_api.php?d_o=0");
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.failed_connect_network), Toast.LENGTH_SHORT).show();
}
break;
case 5:
if (JsonUtils.isNetworkAvailable(getActivity())) {
list.clear();
new MyTask().execute(Config.SERVER_URL + "/banko_api.php?d_o=1");
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.failed_connect_network), Toast.LENGTH_SHORT).show();
}
break;
default:
if (JsonUtils.isNetworkAvailable(getActivity())) {
list.clear();
new MyTask().execute(Config.SERVER_URL + "/banko_api.php?d_o=0");
} else {
Toast.makeText(getActivity(), getResources().getString(R.string.failed_connect_network), Toast.LENGTH_SHORT).show();
}
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Calendar calendar = Calendar.getInstance();
Date today = calendar.getTime();
calendar.add(Calendar.DAY_OF_YEAR, -1);
Date yesterday = calendar.getTime();
calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date tomorrow = calendar.getTime();
DateFormat dateFormat = new SimpleDateFormat("dd/MM EEE");
String todayAsString = dateFormat.format(today);
String tomorrowAsString = dateFormat.format(tomorrow);
String yesterdayAsString = dateFormat.format(yesterday);
// Spinner Drop down elements
List<String> categories = new ArrayList<String>();
categories.add(yesterdayAsString);
categories.add(todayAsString);
categories.add(tomorrowAsString);
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getContext(), R.layout.spinner_item, categories);
dataAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
spinner.setSelection(4);
The problem : first load of the app is calling the data of today (which is the default choice in my spinner) without any problem.
if i choose another element in the spinner it also calls the related data without problem.
now if I want to select back today element in the spinner no data will be brought from the server even when the app at the start up it calls data from the same link and get it.
I get this message in my log :
W/System.err: org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject
The onPostExcute of my Asynktask contains this code:
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (null != progressDialog && progressDialog.isShowing()) {
progressDialog.dismiss();
}
if (null == result || result.length() == 0) {
Toast.makeText(getActivity(), getResources().getString(R.string.failed_connect_network), Toast.LENGTH_SHORT).show();
} else {
try {
Log.d("resultTT",result);
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(JsonConfig.CATEGORY_ARRAY_NAME);
JSONObject objJson = null;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
ItemMatch objItem = new ItemMatch();
objItem.setMatchId(objJson.getString(JsonConfig.Match_ID));
objItem.setMatchTournamentName(objJson.getString(JsonConfig.Match_LEAGUE_NAME));
objItem.setMatchTime(objJson.getString(JsonConfig.Match_TIME));
objItem.setMatchStatus(objJson.getString(JsonConfig.Match_STATUS));
objItem.setMatchLocalTeamName(objJson.getString(JsonConfig.Match_LOCALTEAM_NAME));
objItem.setMatchVisitorTeamName(objJson.getString(JsonConfig.Match_VISITORTEAM_NAME));
objItem.setMatchLocalTeamGoals(objJson.getString(JsonConfig.Match_LOCALTEAM_GOALS));
objItem.setMatchVisitorTeamGoals(objJson.getString(JsonConfig.Match_VISITORTEAM_GOALS));
objItem.setMatchBestOddPercent(objJson.getString(JsonConfig.Match_BEST_ODD_PERCENT));
objItem.setMatchBestOddResult(objJson.getString(JsonConfig.Match_BEST_ODD_RESULT));
list.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
for (int j = 0; j < list.size(); j++) {
object = list.get(j);
array_match_id.add(String.valueOf(object.getMatchId()));
str_match_id = array_match_id.toArray(str_match_id);
array_league_name.add(String.valueOf(object.getMatchTournamentName()));
str_league_name = array_league_name.toArray(str_league_name);
array_match_time.add(String.valueOf(object.getMatchTime()));
str_match_time = array_match_time.toArray(str_match_time);
array_match_status.add(String.valueOf(object.getMatchStatus()));
str_match_status = array_match_status.toArray(str_match_status);
array_match_localteam_name.add(object.getMatchLocalTeamName());
str_match_localteam_name = array_match_localteam_name.toArray(str_match_localteam_name);
array_match_visitorteam_name.add(object.getMatchVisitorTeamName());
str_match_visitorteam_name = array_match_visitorteam_name.toArray(str_match_visitorteam_name);
array_match_localteam_goals.add(object.getMatchLocalTeamGoals());
str_match_localteam_goals = array_match_localteam_goals.toArray(str_match_localteam_goals);
array_match_visitorteam_goals.add(object.getMatchVisitorTeamGoals());
str_match_visitorteam_goals = array_match_visitorteam_goals.toArray(str_match_visitorteam_goals);
array_match_best_odd_percent.add(object.getMatchBestOddPercent());
str_match_best_odd_percent = array_match_best_odd_percent.toArray(str_match_best_odd_percent);
array_match_best_odd_result.add(object.getMatchBestOddResult());
str_match_best_odd_result = array_match_best_odd_result.toArray(str_match_best_odd_result);
}
setAdapterToListView();
}
In the try section of this code u can see I make a log of the result to see what is coming from the server i just get this : D/resultTT: []
and as you see the try is inside the else section so in the if statement of this section i check if the result is null or empty ; but the code passes it and enter the else statement but still showing that the returned result array is empty.
I want some help to find the reason behind this empty returned array even it loads fine at the start up. why can not it get the information after I choose any element in the spinner and then come back to the default (today) element?
UPDATE : this is my php side-server api code
<?php
include_once ('includes/variables.php');
DEFINE ('DB_HOST', $host);
DEFINE ('DB_USER', $user);
DEFINE ('DB_PASSWORD', $pass);
DEFINE ('DB_NAME', $database);
$mysqli = #mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to MySQL');
#mysql_select_db (DB_NAME) OR die ('Could not select the database');
?>
<?php
mysql_query("SET NAMES 'utf8'");
$date_offset = mysql_real_escape_string($_GET[d_o]);
//$date_offset = 0;
if(empty($date_offset) || $date_offset == "0")
{
$date_offset_value = "0";
$query="SELECT a.*, m.match_id, m.match_time, m.en_tournament_name FROM app_banko a inner join matches_of_comments m on m.match_id = a.match_id where a.date_offset = $date_offset_value limit 20";
$resouter = mysql_query($query);
}
else
{
$date_offset_value = $date_offset;
$query="SELECT a.*, m.match_id, m.match_time, m.en_tournament_name FROM app_banko a inner join matches_of_comments m on m.match_id = a.match_id where a.date_offset = $date_offset_value limit 20";
$resouter = mysql_query($query);
}
$set = array();
$total_records = mysql_num_rows($resouter);
if($total_records >= 1){
while ($link = mysql_fetch_array($resouter, MYSQL_ASSOC)){
$set['NewsApp'][] = $link;
}
}
echo $val= str_replace('\\/', '/', json_encode($set));
?>
If you get an array in return when expecting an object, there might be something wrong with the request to the API. One way is to figure it out it set up Wireshark on the development machine to sniff and filter the traffic. Then you can see if your request is faulty.
It is possible that the value of the response argument from the onPostExecute method contains stringified JSONArray, not JSONObject.
You can always test this with:
try:
JSONArray jsonArray = new JSONArray(result);
catch(JSONException e) {
// String `result` is not an array. Parse it as a regular JSONObject.
}
Testing wheter string is an empty json array (depends on it's formatting, especially when it may contain some white characters) checking it's length might be a pretty bad idea.
It all depends how are determined an API endpoints that you are calling.
One more tip at the end. If you are planning to consume REST API I strongly recommend using:
Retrofit - which allows you to easily define interfaces to access your API,
GSON - to automatically convert responses for Java models.
Your result string is an empty array but not an empty string. The empty array is represented as the following string:
String result = "[]";
In that case result.length() is equal to 2.
When parsing JSON you need to know if the parsed object is of type Object or of type Array. The former one is wrapped with braces {}, the later one with square brackets [].
So the following line:
JSONObject mainJson = new JSONObject(result);
Should probably be:
JSONArray mainJson = new JSONArray(result);
But I cannot emphasize enough that you need to know what your API returns if you want to be able to parse it correctly.
EDIT:
Well, json_encode will have a hard time to guess whether it should create a JSON Array or a JSON Object out of the empty array that you created with $set = array();.
Adding objects to the array like you do in your loop makes it obvious for json_encode that it should create a JSON Object.
I don't know if you can force json_encode's behavior, but worst case you could check yourself if the array is empty and return "" or null if the array is empty.
$set = array();
$total_records = mysql_num_rows($resouter);
if ($total_records >= 1) {
while ($link = mysql_fetch_array($resouter, MYSQL_ASSOC)) {
$set['NewsApp'][] = $link;
}
echo $val= str_replace('\\/', '/', json_encode($set));
} else {
echo $val="";
}
please put a check result.isEmpty() in your try block condition may this could solve your problem.
you can not directly get response in string . it can use JSONObject and JSONArray.

Returns zero for all values retrieved from the parse database

I'm using parse backend to store and retrieve the datas for my android app, the storing gets done properly but i have problem in retrieving it. I just went through the parse documentation to retrieve the result but what i get is just 0 for all the retrieved values..im suret that the class exists in the parse cloud with valid values but still i get 0 for all the queries.. this is my code to save:
Toast.makeText(getApplicationContext(),"writing to parse",Toast.LENGTH_SHORT).show();
ParseObject dataObject = new ParseObject("Score");
dataObject.put("correct",correctAnswers);
dataObject.put("wrong",wrongAnswers);
dataObject.put("percent", percentage);
dataObject.saveInBackground();
this is how i get back the saved data
ParseQuery<Score> query = ParseQuery.getQuery("Score");
try {
List<Score> scoreList = query.find();
} catch (ParseException e) {
e.printStackTrace();
}
query = ParseQuery.getQuery("Score");
final Activity ctx = this;
query.findInBackground( new FindCallback<Score>() {
#Override public void done(List<Score> scoreList, ParseException e) {
if ( e == null ) {
ParseObject dataObject = ParseObject.create("Score");
int p = dataObject.getInt("correct");
int q = dataObject.getInt("wrong");
int r = dataObject.getInt("percent");
Toast.makeText(ExamRecordActivity.this,String.valueOf(p),Toast.LENGTH_SHORT).show();
Toast.makeText(ExamRecordActivity.this,String.valueOf(q),Toast.LENGTH_SHORT).show();
Toast.makeText(ExamRecordActivity.this,String.valueOf(r),Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(ctx,
"Error updating questions - please make sure you have internet connection",
Toast.LENGTH_LONG).show();
}
}
});
Inside the done method you are creating a new by calling ParseObject dataObject = ParseObject.create("Score"); and then trying to read values from it without putting any in.
I don't know what the structure of your class is but you need to be iterating through List<Score> scoreList in order to get the queried data.

how to Create new Record in QuikcBlox custome table

Want to create new Record in QuickBlox Custom Table which allready created.
i have Follow the guideline Url and using below method, here i m using my Table name
HashMap<String, Object> fields = new HashMap<String, Object>();
fields.put("User ID",String.valueOf(myID));
fields.put("senderLoginID", ""+mylogin.toString());
fields.put("receiverLoginID", ""+friendLogin.toString());
fields.put("messages", messageString);
fields.put("isRead", false);
QBCustomObject qbCustomObject = new QBCustomObject();
qbCustomObject.setClassName("Movie"); // your Class name
qbCustomObject.setFields(fields);
QBCustomObjects.createObject(qbCustomObject, new QBCallbackImpl() {
#Override
public void onComplete(Result result) {
if (result.isSuccess()) {
QBCustomObjectResult qbCustomObjectResult = (QBCustomObjectResult) result;
QBCustomObject qbCustomObject = qbCustomObjectResult.getCustomObject();
Log.d("New record: ",newCustomObject.toString());
} else {
Log.e("Errors",result.getErrors().toString());
}
}
});
Error getting Like
** '{"errors":{"base":["Forbidden. Need user."]}}'
… Request has been completed with error: [base Forbidden. Need user.]
1st off all, you don't need to use this
fields.put("User ID",String.valueOf(myID));
This field will be filled on the server based on your token information
Next, you have to be logged in in order to create record,
just do the next
http://quickblox.com/developers/SimpleSample-users-android#Sign_In_.26_Social_authorization

Arraylist shows empty after adding items

I have an arraylist, which i used to store json parsed values.but after adding values to arraylist it shows its size as 1.i've attached my code below.pls help me to solve this
public void completed(JSONObject jsonObject) {
login_data = new ArrayList<Login_modal>();
try {
String response=jsonObject.toString();
JSONObject result = new JSONObject(response);
JSONObject res = result.getJSONObject(RES);
String stat = res.getString(STAT);
String username = res.getString(USERNAME);
String useremail = res.getString(USEREMAIL);
String userId = res.getString(USERID);
String userAvatarFile = res.getString(USERAVATARFILE);
String userType = res.getString(USERTYPE);
String authID = res.getString(AUTHID);
String cntr = res.getString(CNTR);
String loggedInOnce = res.getString(LOGGEDINONCE);
String topicarn = res.getString(TOPICARN);
Login_modal login_details = new Login_modal(stat, username, useremail, userId, userAvatarFile, userType, authID, cntr, loggedInOnce, topicarn);
login_details.setStat(STAT);
login_details.setUsername(USERNAME);
login_details.setUseremail(USEREMAIL);
login_details.setUserId(USERID);
login_details.setUserAvatarFile(USERAVATARFILE);
login_details.setUserType(USERTYPE);
login_details.setAuthID(AUTHID);
login_details.setCntr(CNTR);
login_details.setLoggedInOnce(LOGGEDINONCE);
login_details.setTopicarn(TOPICARN);
login_data.add(login_details);
} catch (JSONException e) {
e.printStackTrace();
}
here is my json file
{
"res": {
"stat": "SUCCESS",
"username": "Aggie",
"useremail": "aggie#logicalsteps.net",
"userId": "u55e29ddfe7cbd",
"userAvatarFile": "",
"userType": "SUB",
"authID": "",
"cntr": "",
"loggedInOnce": "",
"topicarn": "arn:aws:sns:us-east-1:080141827424:Demogroup"
}
}
here i am getting arraylist
if(login_data.get(1).equals("SUCCESS")) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
else {
Toast.makeText(Login.this, "Login failed try again", Toast.LENGTH_SHORT).show();
}
error log
FATAL EXCEPTION: main
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
at java.util.ArrayList.get(ArrayList.java:304)
You're doing wrong. correct way is
if(login_data.get(0).getStat().equals("SUCCESS"))
your login_data has only 1 record so you will get this by get(0) 0:index(first element)
login_data.get(0) ----> return Login_modal at 0 position
login_data.get(0).getStat() ----> return Stat of Login_modal at 0 position
Arraylist index starts with 0 and you are using login_data.get(1) and the arraylist size only 1
if(login_data.get(0).equals("SUCCESS")) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
else {
Toast.makeText(Login.this, "Login failed try again", Toast.LENGTH_SHORT).show();
}
Your JSON response keys are in lower case but you are pasring in UPPER case
for example you should parse like this for the rest:
String stat = res.getString("stat");
You already created constructor and again you are using setter method. I'm assuming that in LOGIN_MODEL constructor you are setting every variable.
comment these lines
login_details.setStat(STAT);
login_details.setUsername(USERNAME);
login_details.setUseremail(USEREMAIL);
login_details.setUserId(USERID);
login_details.setUserAvatarFile(USERAVATARFILE);
login_details.setUserType(USERTYPE);
login_details.setAuthID(AUTHID);
login_details.setCntr(CNTR);
login_details.setLoggedInOnce(LOGGEDINONCE);
login_details.setTopicarn(TOPICARN);
common man its typo error. You are passing your json key in arrayList
login_details.setStat(STAT);
It should be
login_details.setStat(stat);
because you have stored value in stat not in STAT, STAT is your JSON key.
And one more point, your arraylist is having only 1 record so instead of login_data.get(1) you need to use login_data.get(0)
if(login_data.get(0).getStat().equalsIgnoreCase("SUCCESS"))
You added only one data.
login_data.add(login_details);
The following is not adding data to the list
login_details.setStat(STAT);
login_details.setUsername(USERNAME);
...
you are setting the value of the properties of the Login_modal modal instance login_details.
and then adding that one Login_modal instance to login_data.
so you will really end up with one.
Here you get exception (Index out of bounds) because you are accessing the 2nd (index 1; 1st is index 0) element of login_data which does not exist.
if(login_data.get(1).equals("SUCCESS")) {

Categories

Resources