usertype value showing null in android - java

Hi In This code I am getting response by using json for that created one map in that I mention key and value.Now That value storing in one variable for that I wrote like this
String usertype = usertypeMap.get(user_type[i]);
But The usertype showing null can any one please help me where I did mistake.
java
String username1 = usname.getText().toString();
String password = pword.getText().toString();
queryString = "username=" + username1 + "&password="
+ password ;
String user_type1 = DatabaseUtility.executeQueryPhp("usertype",queryString);
System.out.print(user_type1);
try
{
JSONArray JA = new JSONArray(user_type1);
username = new String[JA.length()];
user_type = new String[JA.length()];
for(int i=0;i<JA.length();i++)
{
username[i] = JA.getJSONObject(i).getString("username");
user_type[i] = JA.getJSONObject(i).getString("user_type");
usertypeMap.put(username[i],user_type[i]);
}
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
e.printStackTrace();
}
String usertype = usertypeMap.get(user_type[i]);
try{
queryString = "username=" + username1 + "&password="
+ password +"&user_type="+usertype;
final String data = DatabaseUtility.executeQueryPhp("login",queryString);

You are getting value from the value
Map is(KEY,VALUE). In your code, key is username[i] value is user_type[i]. But you getting the value like this
String usertype = usertypeMap.get(user_type[i]);
try using like this
String usertype = usertypeMap.get(username[i]);

Related

Java REST API upon building string after get request replace null values with string vale

I am currently working on a Java application where I have an AsyncTask function get data from an API, then have a line reader and string builder create a large string, which I then pass to the postExecute function where I convert that string into a JSON object. I have tried creating a function that takes the string before post execute and replaces all null with "N/A", I have also tried checking in the String builder function but neither seem to make any changes to the null value. Here is an example of what the code looks like. I believe the error occurs when The string is converted into the JSON Object. This is a school project and I am not allowed to use external libraries.
String Builder:
BufferedReader reader = new BufferedReader(new InputStreamReader(httpClient.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
if (line.contains(null) || line.contains(""))
line += "N/A";
else
continue;
builder.append(line + "\n");
}
replaceNull Function:
public String removeUnwantedVal(String message) {
if (message.contains("null")) {
String replacement = "N/A";
message.replaceAll(null, replacement);
}
return message;
}
Post Execute JSON Object:
protected void onPostExecute(String message) {
TextView tv = findViewById(R.id.display);
System.out.println(message);
try {
JSONObject jsonAddress = new JSONObject(message);
// DISPLAY INFORMATION
String requesterIP = jsonAddress.getString("requester-ip");
String execTime = jsonAddress.getString("execution-time");
ipInfo.setIPAndTime(requesterIP, execTime);
// GEOGRAPHY
JSONObject geo = jsonAddress.getJSONObject("geo");
String countryName = geo.getString("country-name");
String capital = geo.getString("capital");
String iso = geo.getString("country-iso-code");
String city = geo.getString("city");
double longitude = geo.getDouble("longitude");
double latitude = geo.getDouble("latitude");
location = new Location(countryName, capital, iso, city, longitude, latitude);
// CURRENCY
JSONObject currency = jsonAddress.getJSONObject("currency");
String currencyNativeName = currency.getString("native-name");
String currencyCode = currency.getString("code");
String currencyName = currency.getString("name");
String currencySymbol = currency.getString("symbol");
Currency = new Currency(currencyNativeName, currencyCode, currencyName, currencySymbol);
// ASN
JSONObject asn = jsonAddress.getJSONObject("asn");
String asnName = asn.getString("name");
String asnDomain = asn.getString("domain");
String asnOrganization = asn.getString("organization");
String asnCode = asn.getString("asn");
String asnType = asn.getString("type");
ASN = new ASN(asnName, asnDomain, asnOrganization, asnCode, asnType);
// TIMEZONE
JSONObject timezone = jsonAddress.getJSONObject("timezone");
String timezoneName = timezone.getString("microsoft-name");
String dateTime = timezone.getString("date-time");
String ianaName = timezone.getString("iana-name");
Timezone = new Timezone(timezoneName, dateTime, ianaName);
// SECURITY
JSONObject security = jsonAddress.getJSONObject("security");
boolean isCrawler = security.getBoolean("is-crawler");
boolean isProxy = security.getBoolean("is-proxy");
boolean isTor = security.getBoolean("is-tor");
Security = new Security(isCrawler, isProxy, isTor);
container = new IPContainer(ipInfo, Currency, location, Security, ASN, Timezone);
tv.setText(container.displayGeneral());
} catch (JSONException e) {
tv.setText(e.toString());
e.printStackTrace();
}
}
I have resolved the issue. When I was getting the code I thought that null values could not be displayed, this was incorrect. The problem was that I was trying to create an object out of null, sometimes the value came back as null instead of as an object. Sorry, beginner coder :)

Retrieve wrong data

This is MySQL data (Table work details)
The data retrieved by following code. Noted that I want to retrieve everything except id and twd .
private void showForce(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
JSONArray result = jsonObject.getJSONArray(Configs.TAG_JSON_ARRAY);
JSONObject c = result.getJSONObject(0);
String project = c.getString(Configs.TAG_PROJECT).trim();
RetrieveProject(project);
String description = c.getString(Configs.TAG_WORKDESCRIPTION).trim();
int per = c.getInt(Configs.TAG_PERCENTAGE);
String in=c.getString(Configs.TAG_IN).trim();
String time[]=in.split(":", 3);
String time1=time[0]+":"+time[1];
String out=c.getString(Configs.TAG_OUT).trim();
String timeOut[]=out.split(":", 3);
String timeout=timeOut[0]+":"+timeOut[1];
seekBar.setProgress(per);
progressText.setText("Covered:" + "" + seekBar.getProgress() + "/" + seekBar.getMax());
String From=c.getString(Configs.TAG_From).trim();
String To=c.getString(Configs.TAG_To).trim();
String Mil=c.getString(Configs.TAG_Mileage).trim();
String Hotel=c.getString(Configs.TAG_Hotel).trim();
String Toll=c.getString(Configs.TAG_Toll).trim();
String Business=c.getString(Configs.TAG_Business).trim();
TimeIn.setText(time1);
TimeOut.setText(timeout);
Description.setText(description);
mileage.setText(Mil);
hotel.setText(Hotel);
business.setText(Business);
toll.setText(Toll);
travelFrom.setText(From);
travelTo.setText(To);
} catch (JSONException e) {
e.printStackTrace();
}
PhP
<?php
define('HOST','localhost');
define('USER','spiral69_wp178');
define('PASS','q1w2e3r4');
define('DB','spiral69_androiddb');
$con = mysqli_connect(HOST,USER,PASS,DB) or die('unable to connect');
$id=$_GET['id'];
$sql = "select * from work_details WHERE id= '". $id."'";
$res = mysqli_query($con,$sql);
$result=array();
while($row=mysqli_fetch_array($res)){
array_push($result,array('id'=>$row[0],'project'=>$row[1],'work_description'=>$row[2],'percentage'=>$row[3],'timeIn'=>$row[4],
'timeOut'=>$row[5],'travel_From'=>$row[6],'travel_To'=>$row[7],'mileage'=>$row[8],'hotel_accom'=>$row[9],'toll'=>$row[10],'business_expenses'=>$row[11]));
}
echo (json_encode(array("result"=>$result)));
mysqli_close($con);
?>
Project,Description,TimeIn,TimeOut,per display correctly but From, To, Mil,Hotel,Toll,Business are incorrect.
And this are the output I get in setText.(Incorrect)
travelFrom.setText(From); I get 63 (twd column)
travelTo.setText(To); I get df (travel_from column)
mileage.setText(Mil); I get a....
it is just that you missed 'twd' column when you are setting up data in json object in PHP script... the index for 'travel_from' is 7 and not six and same is applicable to other fields after that!!!

Not able to fetch all data from facebook access token in java servlet

I am trying to fetch fb user's "friend list" and his/her "about" but when i do i am getting null value of certain field like i comment below.
System.out.println(loginUser.getId()); //show id
System.out.println(loginUser.getName()); //Show Name
System.out.println(loginUser.getFirstName()); //show null
System.out.println(loginUser.getGender()); //show null
System.out.println(loginUser.getAbout()); //show null
I've been trying the graph-api explorer to see what I'm getting for gender
Its shows here
Code:
String code = request.getParameter("code");
String URLEncodedRedirectURI = URLEncoder.encode("http://localhost:8080/bitspedia-fetchfbfriends/FriendsListServlet");
String MY_ACCESS_TOKEN = "";
String authURL = "https://graph.facebook.com/oauth/access_token?" +
"client_id=" + FriendsListServlet.APP_ID + "&" +
"redirect_uri=" + URLEncodedRedirectURI + "&" +
"client_secret=" + FriendsListServlet.APP_SECRET + "&" +
"code=" + code;
URL url = new URL(authURL);
String result = readURL(url);
String[] pairs = result.split("&");
for (String pair : pairs) {
String[] kv = pair.split("=");
if (kv[0].equals("access_token")) {
MY_ACCESS_TOKEN = kv[1];
}
}
FacebookClient facebookClient = new DefaultFacebookClient(MY_ACCESS_TOKEN, FriendsListServlet.APP_SECRET);
Connection<User> friends = null;
try {
User loginUser = facebookClient.fetchObject("me", User.class);
request.setAttribute("loginUser", loginUser);
friends = facebookClient.fetchConnection("/me/friends", User.class);
System.out.println(loginUser.getId()); //shows id
System.out.println(loginUser.getName()); //Shows name
System.out.println(loginUser.getFirstName()); //shows null
System.out.println(loginUser.getWebsite()); //shows null
System.out.println(loginUser.getAbout()); //shows null
} catch (FacebookException e) {
e.printStackTrace();
}
List<User> friendsList = friends.getData();
It has very small issue, you didn't provide parameter of null showing value so doing small changes it works fine.
User loginUser = facebookClient.fetchObject("me", `Parameter.with("fields","first_name,last_name,posts")););`

Deserializing Gson NullPointer?

I am trying to parse JSON to get some values.
{
"username":"shobhit#gmail.com",
"roles:
{
"ROLE_Student_Trial":true,
"ROLE_student":true,
"ROLE_Student_Unlimited":true
},
"type":"student",
"lastLogin":1441305986000,
"token":"123"
}
This is how I am deSerializing it
JsonObject obj = new JsonParser().parse(jsonString).getAsJsonObject();
String userName = obj.get("username").getAsString();
JsonObject roles = obj.get("roles").getAsJsonObject();
Boolean isTrial = roles.get("ROLE_Student_Trial").getAsBoolean();
Boolean isStudent = roles.get("ROLE_Student").getAsBoolean();
Boolean isUnlimited = roles.get("ROLE_Student_Unlimited").getAsBoolean(); // LoginTest.java:31
long lastLogin = obj.get("lastLogin").getAsLong();
int token = obj.get("token").getAsInt();
String type = obj.get("type").getAsString();
System.out.println(userName);
if(isTrial){
System.out.println("Student trial is on last login " + timeConverter(lastLogin));
}
if(isStudent){
System.out.println("Student access level");
}
if(isUnlimited){
System.out.println("Student is unlimited as " + type + " and its token = " + token);
}
I was trying to get values of inner JSON,
but I am getting NullPointerException.
Exception in thread "main" java.lang.NullPointerException
at loginActivityHttpURL.LoginTest.main(LoginTest.java:31)
I am answering to my own question.
JSON is case sensitive, so at ("ROLE_Student") gson wouldn't find any value. Instead I corrected it with ("ROLE_student") and it worked.
Thanks to #Tobia Tesan
Change this line
Boolean isStudent = roles.get("ROLE_Student").getAsBoolean();
to
Boolean isStudent = roles.get("ROLE_student").getAsBoolean();

Saving the values of a string to another class and retrieving it

I am currently trying to save the values of a string to another class file in JAVA called Memory.JAVA. The reason why I am doing this is because variables are not saved outside the Try - Catch Blocks. Therefore I initiate the class in the try catch block by using this code:
Memory mem = new Memory();
And then when I want to save a string, I use the following:
mem.brother1ID = "Whatever";
The reason why I am not creating it as a new String is because in the Memory class, I have already initiated this string. To test that this has been saved, I have used System.out.println to print out the result which in this case was "Whatever" but when I try to get the same result printed out in the same class, I get the result "null". Does anyone have any suggestions regarding my issue? Please feel free to comment below. Thanks!
UPDATE:
Some code posted below:
private void searchFieldKeyReleased(java.awt.event.KeyEvent evt) {
try {
Memory mem = new Memory();
String sql = "select * from userInfo where firstName= ? OR lastname = ?";
pst=conn.prepareStatement(sql);
pst.setString(1, searchField.getText());
pst.setString(2, searchField.getText());
rs=pst.executeQuery();
if(rs.next()) {
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
String placeOfResidence = rs.getString("placeOfResidence");
String employmentStatus = rs.getString("employmentStatus");
String currentEmployer = rs.getString("currentEmployer");
String taxStatus = rs.getString("taxStatus");
String dateOfBirth = rs.getString("dateOfBirth");
String mother = rs.getString("mother");
String father = rs.getString("father");
String brother1 = rs.getString("brother1");
String brother2 = rs.getString("brother2");
String brother3 = rs.getString("brother3");
String brother4 = rs.getString("brother4");
String brother5 = rs.getString("brother5");
String sister1 = rs.getString("sister1");
String sister2 = rs.getString("sister2");
String sister3 = rs.getString("sister3");
String sister4 = rs.getString("sister4");
String sister5 = rs.getString("sister5");
mem.brother1ID = rs.getString("brother1ID");
mem.brother2ID = rs.getString("brother2ID");
mem.brother3ID = rs.getString("brother3ID");
mem.brother4ID = rs.getString("brother4ID");
mem.brother5ID = rs.getString("brother5ID");
mem.sister1ID = rs.getString("sister1ID");
mem.sister2ID = rs.getString("sister2ID");
mem.sister3ID = rs.getString("sister3ID");
mem.sister4ID = rs.getString("sister4ID");
mem.sister5ID = rs.getString("sister5ID");
mem.fatherID = rs.getString("fatherID");
mem.motherID = rs.getString("motherID");
System.out.println(mem.brother1ID);
System.out.println(firstName + " " + lastName);
firstNameField.setText(firstName);
lastNameField.setText(lastName);
placeOfResidenceField.setText(placeOfResidence);
employmentStatusField.setText(employmentStatus);
currentEmployerField.setText(currentEmployer);
taxStatusField.setText(taxStatus);
dateOfBirthField.setText(dateOfBirth);
motherField.setText(mother);
fatherField.setText(father);
brothersField1.setText(brother1);
brothersField2.setText(brother2);
brothersField3.setText(brother3);
brothersField4.setText(brother4);
brothersField5.setText(brother5);
sisterField1.setText(sister1);
sisterField2.setText(sister2);
sisterField3.setText(sister3);
sisterField4.setText(sister4);
sisterField5.setText(sister5);
}
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
And this is when I try to get the same results of System.out.println as before:
private void brotherViewButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Memory mem = new Memory();
String sql = "select * from userInfo where id=?";
pst=conn.prepareStatement(sql);
String IDNO = mem.brother1ID;
System.out.println(IDNO);
pst.setString(1, IDNO);
rs=pst.executeQuery();
if(rs.next()) {
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
String placeOfResidence = rs.getString("placeOfResidence");
String employmentStatus = rs.getString("employmentStatus");
String currentEmployer = rs.getString("currentEmployer");
String taxStatus = rs.getString("taxStatus");
String dateOfBirth = rs.getString("dateOfBirth");
String mother = rs.getString("mother");
String father = rs.getString("father");
String brother1 = rs.getString("brother1");
String brother2 = rs.getString("brother2");
String brother3 = rs.getString("brother3");
String brother4 = rs.getString("brother4");
String brother5 = rs.getString("brother5");
String sister1 = rs.getString("sister1");
String sister2 = rs.getString("sister2");
String sister3 = rs.getString("sister3");
String sister4 = rs.getString("sister4");
String sister5 = rs.getString("sister5");
System.out.println(firstName + " " + lastName);
firstNameField.setText(firstName);
lastNameField.setText(lastName);
placeOfResidenceField.setText(placeOfResidence);
employmentStatusField.setText(employmentStatus);
currentEmployerField.setText(currentEmployer);
taxStatusField.setText(taxStatus);
dateOfBirthField.setText(dateOfBirth);
motherField.setText(mother);
fatherField.setText(father);
brothersField1.setText(brother1);
brothersField2.setText(brother2);
brothersField3.setText(brother3);
brothersField4.setText(brother4);
brothersField5.setText(brother5);
sisterField1.setText(sister1);
sisterField2.setText(sister2);
sisterField3.setText(sister3);
sisterField4.setText(sister4);
sisterField5.setText(sister5);
}
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
The reason the value brother1ID in your Memory object is null is because you're using a new instance of that object.
I strongly recommend you read up on how object instances are scoped in Java, and what it means to create a new instance, versus using an existing one.
For example, when you do this:
Memory mem = new Memory();
mem.brother1ID = "1234";
mem = new Memory();
System.out.println(mem.brother1ID);
The value printed will be null. This is because you're using a new instance of that class. If you wanted to maintain the values throughout multiple method calls, your best bet might be to save the Memory object as an instance variable of whatever class contains the methods you've shown. i.e.:
private Memory memory = new Memory();
...
private void searchFieldKeyReleased(java.awt.event.KeyEvent evt) {
// Use 'this.memory'
this.memory.brother1ID = "1234";
//(or)
System.out.println(this.memory.brother1ID);
}
private void brotherViewButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// Use 'this.memory'
}
Please look at here
try {
Memory mem = new Memory();
String sql = "select * from userInfo where id=?";
pst=conn.prepareStatement(sql);
String IDNO = mem.brother1ID;
System.out.println(IDNO);
You are creating the object of Memory and not setting any value.
then you are trying to print the brotherId which will be null, all String variables will be initialised to null, that is why you are getting 'null'. what you can do is put the printing statement out of the try catch block at he bottom , if there are any records in your database, it will print out the last records brotherId.

Categories

Resources