Retrieve wrong data - java

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!!!

Related

How to? - Insert a string into a php file before the same file does a GET

I have successfully connected my android app to a mysql database and did a read from the database which is displaying all the rows from a table in the app. I want to narrow this down so it only displays the rows which correspond with the users id. I have the usersID stored as a shared preference from when they log into the app. I need my php file to recognise the users id and then use this id as part of the query so it only displays the appropriate rows.I am having trouble trying to set this code up and would benefit from some help. Please see the php and java below.
PHP CODE:
<?php
include('conn.php');
if(isset($_GET['userId'])){//The PHP file doesnt work with these two lines
$getId = $_GET['userId'];
$query = "SELECT * FROM Cbt WHERE userId = '$getId'";
$result = mysqli_query($conn, $query);
$json_array = array();
while ($row = mysqli_fetch_assoc($result)){
$json_array[] =$row;
}
}
echo json_encode($json_array);
JAVA CODE:
loginPref = getSharedPreferences("loginPref", Context.MODE_PRIVATE);
final int userId = loginPref.getInt("userId", 0);
textViewResult = findViewById(R.id.text_viewer_result);
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
Api api = retrofit.create(Api.class);
Call<List<WorkoutLogRecycler>> call = api.getLogs();
call.enqueue(new Callback<List<WorkoutLogRecycler>>() {
#Override
public void onResponse(Call<List<WorkoutLogRecycler>> call, Response<List<WorkoutLogRecycler>> response) {
if (!response.isSuccessful()) {
textViewResult.setText("Code:"+response.code());
return;
}
List<WorkoutLogRecycler> workoutLogRecyclers = response.body();
for (WorkoutLogRecycler workoutLogRecycler : workoutLogRecyclers){
String content ="";
content += "cbtId: " + workoutLogRecycler.getCbtId() +"\n";
content += "userId: " + workoutLogRecycler.getUserId() +"\n";
content += "moodBefore: " + workoutLogRecycler.getMoodBefore() +"\n";
content += "automaticThought: " + workoutLogRecycler.getAutomaticThought() +"\n";
content += "distortions: " + workoutLogRecycler.getDistortions() +"\n";
content += "challengeTought: " + workoutLogRecycler.getChallengeThought() +"\n";
content += "alternativeThought: " + workoutLogRecycler.getAlternativeThought() +"\n";
content += "moodAfter: " + workoutLogRecycler.getMoodAfter() +"\n";
textViewResult.append(content);
}
}
#Override
public void onFailure(Call<List<WorkoutLogRecycler>> call, Throwable t) {
textViewResult.setText(t.getMessage());
}
});
API CODE:
public interface Api {
#FormUrlEncoded
#POST("insert.php")
Call<ResponseBody> insertLog(
#Field("userId") int userId,
#Field("moodBefore") int moodBefore,
#Field("automaticThought") String automaticThought,
#Field("distortions") int distortions,
#Field("challengeThought") String challengeThought,
#Field("alternativeThought") String alternativeThought,
#Field("moodAfter") int moodAfter
);
#GET("read.php")
Call<List<WorkoutLogRecycler>> getLogs();
Ok so your API url getLogs() needs a parameter that will be passed to the php script
#GET("read.php")
Call<List<WorkoutLogRecycler>> getLogs(#Query("userId") String userId);
and then change the line
Call<List<WorkoutLogRecycler>> call = api.getLogs();
// to
Call<List<WorkoutLogRecycler>> call = api.getLogs(userId);
Check if it works. Basically you execute a request that is provided in the .baseUrl() but you don't attach any param to it. When you use GET on the server side, the url should contain some data attached. Like: https://www.api.com?userId=2.
Then $_GET['userId'] can extract userId value from the url.
Retrofit attach params for you using #Query adnotation.
From a first PHP sight, I can tell that you are not passing the $getId correctly within your query. What you should do is: $query = "SELECT * FROM Cbt WHERE userId = " . $getId;
Besides that, check this way of using mysqli queries by assigning them a variable.

How to parse nested JSON Using Android? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to parse URL to get JSON response and particular values from that response. I dont have a sample code. Please give me a simple solution.
Below I have posted my URL and Response. I want to GET "School", Name" and Result values.
http://sample.com/login/username/ <username> /password <password>?
{
"response":{
"School":"SBOA",
"Name":"Anitha",
"Class":"Tenth",
},
"Result":"Good",
}
My Code :
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView output = (TextView) findViewById(R.id.textView1);
String strJson="URL";
String data = "";
System.out.println(strJson);
try {
JSONObject jsonRootObject = new JSONObject(strJson);
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("response");
System.out.println(jsonRootObject);
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
// int id = Integer.parseInt(jsonObject.optString("id").toString());
String name = jsonObject.optString("School").toString();
// float salary = Float.parseFloat(jsonObject.optString("salary").toString());
// data += "Node"+i+" : \n id= "+ id +" \n Name= "+ name +" \n Salary= "+ salary +" \n ";*/
}
//output.setText(data);
} catch (JSONException e) {e.printStackTrace();}
}
}
To read exactly that JSON, use this:
/** Verify that your strJson string contains this:
* {
* "response":{
* "School":"SBOA",
* "Name":"Anitha",
* "Class":"Tenth",
* },
* "Result":"Good",
* }
*/
String strJson = ??;
Log.d("TAG", "strJson: " + strJson);
try {
JSONObject jsonRootObject = new JSONObject(strJson);
JSONObject response = jsonRootObject.getJsonObject("response");
String schoolString = response.getString("School");
String nameString = response.getString("Name");
String classString = response.getString("Class");
String result = jsonRootObject.getString("Result");
} catch(JSONException e) {
Log.e("TAG", "Error reading json: " + jsonRootObject.toString());
}
If you have a JSONObject named json then follow this for getting school value
try{
jsonRootObject .getJSONObject("response").getString("School");
}catch(JSONException e)
{
e.printStackTrace();
}

usertype value showing null in android

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]);

java.lang.NullPointerException when trying to parse XML

This problem really has me scratching my head.
I have a chat application that parses xml from the server. It is successful parsing the message text, msg id, but I am getting a nullpointerException for the UserID but I am pulling it from the same location. Please help
// Get messages
NodeList messageList = documentElement.getElementsByTagName("MESSAGE");
ret.messages = new ChatStruct[messageList.getLength()];
Log.v("response","Message Length " + messageList.getLength());
for (int i = 0; i < messageList.getLength(); i++) {
Element messageNode = (Element) messageList.item(i);
ret.messages[i] = new ChatStruct();
// Get messageId
try {
Element messageIdNode = (Element) messageNode.getElementsByTagName("ID").item(0);
String messageId = messageIdNode.getFirstChild().getNodeValue();
System.out.println("messageId = " + messageId);
ret.messages[i].id = Long.parseLong(messageId);
//Log.v("Util","Message ID " + Long.parseLong(messageId));
} catch (Exception e) {
ret.messages[i].id = 0l;
// e.printStackTrace();
}
// Get text
try {
Element textNode = (Element) messageNode.getElementsByTagName("TEXT").item(0);
String text = textNode.getFirstChild().getNodeValue();
System.out.println("text = " + text);
ret.messages[i].textMessage = text.trim();
//Log.v("Util","Message text " + text.trim());
} catch (Exception e) {
ret.messages[i].textMessage = "";
// e.printStackTrace();
}
// Get userId
try {
//ret.messages[i].userId = 1;
//Log.v("Util # userID node","userID should be 1");
Element userIdNode = (Element) messageNode.getElementsByTagName("USERID").item(0);
Log.i("Util # userID node","userIdNode set");
String userId = userIdNode.getFirstChild().getNodeValue();
//String userId = "1";
Log.i("Util # userID node","userId String set");
System.out.println("userId = " + userId);
ret.messages[i].userId = Long.parseLong(userId);
//ret.messages[i].userId = 1;
} catch (Exception e) {
Log.v("Util # userID node", "there was an error " + e);
ret.messages[i].userId = 0l;
// e.printStackTrace();
}
I can hard code the string and it works but other than that the error occurs at
String userId = userIdNode.getFirstChild().getNodeValue();
It makes it up to commented line of code confirming the userIDNode is set
I can't figure out why userID is not coming in from the server here is the XML:
<MESSAGE>
<ID><?php echo $row_shouts['msgid']; ?></ID>
<USERID><?php echo $row_shouts['userid']; ?></USERID>
<GENDER><?php echo $row_shouts['gender']; ?></GENDER>
<ONLINE><?php echo $row_shouts['account_status'];?></ONLINE>
<TDATE><?php echo datee("h:i:s M, d Y", strtotime($row_shouts['date'])); ?></TDATE>
<ICONID><?php echo $iconid; ?></ICONID>
<PIC><?php echo $PIC; ?></PIC>
<MSGPIC><?php echo $row_shouts['media']; ?></MSGPIC>
<PICDATE><?php echo strtotime($row_shouts['picdate']); ?></PICDATE>
<ALIAS><![CDATA[<?php echo $row_shouts['nickname'];?>]]></ALIAS>
<TEXT><![CDATA[<?php echo $mesg;?>]]></TEXT>
</MESSAGE>
Did you check with the DTD file for the supplied Xml, May be USERID is not clearly defined there.
[please share the error logs]
What's the execption say if you print the stack trace? It might be because the user id isn't a long and you're trying to parse it. I don't see any errors in the retrieval of the user id.

iOS5: Unable to read value from JSON using NSJSONSerialization

I am trying to parse JSON data. The data is an Array with objects inside it.
This is the JSON array I get from the URL:
["{content:Airfare}",
"{content:Dues \/ Subscriptions}",
"{content:Education \/ Training}",
"{content:Entertainment}",
"{content:GS-OCWD}",
"{content:GS-OCWE}",
"{content:GS-Shift A}",
"{content:GS-Shift B}",
"{content:GS-Shift C}",
"{content:Ground Transportation}",
"{content:Legal Fees}",
"{content:Lodging}",
"{content:Meals}",
"{content:Mileage}",
"{content:Office Supplies}",
"{content:Other Expenses}",
"{content:Prof. Dues & Memberships}",
"{content:Rental Car}",
"{content:Telephone}",
"{content:Telephone \/ Internet}",
"{content:Tolls \/ Parking}"]
This is the code for parsing the JSON array in my .m file
NSError *error = nil;
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://localhost:8080/de.vogella.jersey.final/rest/notes"]];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: jsonData options: NSJSONReadingMutableContainers error: &error];
if (!jsonArray) {
NSLog(#"Error parsing JSON: %#",error);
} else {
for(NSDictionary *item in jsonArray) {
NSLog(#"Item: %#", [item objectForKey:#"content"]);
[_identificationTypes1 addObject:item];
}
}
When the line NSLog(#"Item: %#", [item objectForKey:#"content"]); is executed the app crashes and gives a [__NSCFString objectForKey:]: unrecognized selector error. It is unable to read the key content. If I change the line to NSLog(#"Item: %#", item); I can see all the values like {content:Airfare}. I just need the Airfare value. Can someone help me
This is the code to generate the JSON. I am using Jersey and JAVA.
Can you help me with the JSON format from the URL? This is my DAO code:
public JSONArray getAllNotes()
{
PreparedStatement prepStmt = null;
List<Note> notes = new ArrayList<Note>();
try {
String cSQL = "SELECT EXPENDITURE_TYPE FROM PA_ONLINE_EXPENDITURE_TYPES_V;
prepStmt = connection.prepareStatement(cSQL);
ResultSet result = prepStmt.executeQuery();
while (result.next())
{
Note note = new Note();
//note.setNoteId(result.getInt(1));
note.setContent(result.getString(1));
//note.setCreatedDate( new java.util.Date(result.getDate(3).getTime()));
notes.add(note);
}
return new JSONArray(notes);
} catch (SQLException e) {
e.printStackTrace();
prepStmt = null;
return null;
}
}
This is the POJO method:
#Override
public String toString() {
//return "{Content:"+content+"}" ;
return "ExpType [content=" + content + "]";
}
This is the method that calls the DAO method:
#GET
#Produces({MediaType.APPLICATION_JSON})
public JSONArray getNotes() {
return dao.getAllNotes();
}
Your JSON is wrong. It's just an array of strings and that's why you're getting this error. What it really should be like is:
[{"content":"Airfare"},
{"content":"Dues \/ Subscriptions"},
{"content":"Education \/ Training"},
... etc]

Categories

Resources