I try to write a simple php file, which checks, whether a mysql value exists or not.
For this, I need to parse a simple string from json to android.
e.g: when the value exists, the string is "yes" and when it doesnt exists the string is "no".
Meanwhile I have tried a lot of "solutions", but nothing works.
To do that I usually use this:
$abfrage = "
SELECT
Something
FROM
somewhere
WHERE
This=$that"
;
$link = mysql_query($abfrage) OR die("Error:"+mysql_error());
while($line = mysql_fetch_assoc($link)){
$new=$line;
}
print(json_encode($new));
and in Android:
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try
{
System.out.println(result);
json_data = new JSONObject(result);
String name=(json_data.getString("something"));
Log.e("pass 3", "connection success ");
}
catch(Exception e)
{
Log.e("result:", result.toString());
}
}
This works well, an the the value of the String "name" is the value of "something".
But now my question:
Is it possible to save a string in PHP and parse them to android?
This is what i got:
$abfrage = "SELECT Something FROM somewhere WHERE This = '$that' LIMIT 1";
// Proof whether the value exists or not
$read = mysql_db_query($db, $abfrage);
if (mysql_num_rows($read) == 0){
$value="no";
}
else{
$value="yes";
};
print json_encode($value);
And in JAVA:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/test.php");
HttpResponse response = httpclient.execute(httppost);
String str = EntityUtils.toString(response.getEntity());
System.out.println(""+str); //prints: yes
if(str=="yes") System.out.println("ok"); //not called
if(str=="no") System.out.println("nope"); //not called
I am not sure how you implemented it, but I assume that you execute PHP script from java code with something like this:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/sample/sample.php");
HttpResponse response = httpclient.execute(httppost);
Then simply use:
String str = EntityUtils.toString(response.getEntity());
Use
Log.d("Title", "Message");
To display messages in Logcat console.
I faced this problem months before:
The problem is, that the String str, not only contains the word "yes". It also contains different letters/symbols, which are not displayed in Android/Eclipse. So you have to manually delete these letters by simply calling substring(int start, int end)
Try this:
String str = EntityUtils.toString(response.getEntity());
int number= str.length();
System.out.println("str-length"+number); //You will see not the length of 3 (for yes)
String s2= str.substring(0, 3); //short the string
System.out.println("String s2"+s2);
if(s2.equals("yes"))Log.d("Titles", str);
Related
I am going to get the JSON from the localhost db. Then, I want to put the json into ArrayList. I want to call the parseJSON function. But the JSON is null. Where I should call the function, thanks so much:))
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
StringBuilder sb = new StringBuilder();
InputStream input = con.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(input));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
parseJSON(json);
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON(
);
getJSON.execute();
}
private void parseJSON(String json) {
Gson gson = new Gson();
Type type = new TypeToken<List<EssayElement>>(){}.getType();
List<EssayElement> mList = gson.fromJson(json, type);
for (EssayElement essayElement : mList){
Log.i("Message: " +
"", essayElement.id + "-" + essayElement.title + "-" + essayElement.essay + "-" + essayElement.date + "-" + essayElement.time);
}
}
null object reference with String"json"
I would suggest using a proper http library that handles making requests for you like Volley or Retrofit... JSON and Error handling are also builtin, so AsyncTask can completely be removed for that purpose
But what you have is fine, only json shouldn't be used after the while loop, it's only the last line of the http response, not the full json (assuming there's multiple lines)
You should really consider parsing the results in the onPostExecute, and possibly even having the parse method return an actual object, or display to the UI
You are appending the string to StringBuilder sb = new StringBuilder();. You have to call like this parseJSON(sb.toString()); cause String json is just a pointer doesn't hold the actual string, you want.
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
String json = sb.toString();
You can instead use my code snippet it's working fine for me. now you can use son variable for your private void parseJSON(String json) function.
I am using gson library to get the json from an http request.
Everything works fine, except the part where I compare the string I received from the request. Even if the string are exactly the same, for some reason string.equals method fails. And as output it prints always different dates.
What is the reason for this behaviour? What am I missing here?
BufferedReader br;
try{
String url = "http://date.jsontest.com/";
URL request_url = new URL(url);
HttpURLConnection conn = (HttpURLConnection)request_url.openConnection();
conn.setRequestMethod("GET");
if (200 == conn.getResponseCode()){
br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String jsonLine = "";
String line ;
while ((line = br.readLine()) != null) {
jsonLine += line;
}
JsonElement jelement = new JsonParser().parse(jsonLine);
JsonObject jobject = jelement.getAsJsonObject();
try{
String result = jobject.get("date").toString();
System.out.println("res: " + result);
if(result.equals("05-29-2017"))
System.out.println("Same date");
else
System.out.println("different date");
}
catch (NullPointerException ex){ }
}
}
catch (JsonSyntaxException ex){}
catch (IOException ex) {}
String result = jobject.get("date").toString();
The above line returns String representation of date, i.e. with quotes around it : "05-29-2017" and that's why equals method returns false ("\"05-29-2017\"".equals("05-29-2017") will be false due to double quotes in the start and end)
If you want the actual value, you need to use getAsString method, e.g. following should work:
String result = jobject.get("date").getAsString();
if(result.equals("05-29-2017"))
System.out.println("Same date");
else
System.out.println("different date");
I have the below error. I know I have to encode the result from string
07-08 21:26:51.348: E/2(22265): <!-- End Of Analytics Code -->
07-08 21:26:51.353: E/Fail 3(22265): org.json.JSONException: Value 1 of type java.lang.String cannot be converted to JSONObject
I though the below will convert it . but still facing error.
JSONObject json_data = new JSONObject(result);
JSONArray menuObject = new JSONArray(json_data.getString("code"));
This is my code
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
System.out.println(result);
Log.e(" 2",result );
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try
{
JSONObject json_data = new JSONObject(result);
JSONArray menuObject = new JSONArray(json_data.getString("code"));
System.out.println("length="+menuObject.length());
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
this is php code
<?php
$host='mysql12.000webhost.com';
$uname='a6901827_moudiz';
$pwd='*****';
$db="a6901827_justed";
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
$id=$_REQUEST['id'];
$name=$_REQUEST['name'];
mysql_query('insert into samle values($id,$name)',$con);
print(json_encode("1"));
mysql_close($con);
?>
Please I need to insert data in the database and return value.
You are returning the JSON String "1", but are trying to parse it as JSONObject.
A JSONObject in expects an actual JSON object that starts with { and ending with }. A string is a JSON value and not a JSONObject. That's why the String "1" cannot be converted to a JSONObject.
You could wrap the return value into a PHP Array:
array("value" => "1")
When you encode that into JSON, it will look like this:
{"value":"1"}
Then on the Java client, parse it as a JSONObject and get the string attribute that is named "value".
Or you could just parse it differently on the Java side. (by not using JSONObject).
I need to parse json object for this url
I have used following code
private void parse(String url2) throws MalformedURLException, IOException,JSONException {
// TODO Auto-generated method stub
InputStream is = new URL(url2).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
for(int i=0;i<valArray.length();i++)
{
String p = nameArray.getString(i) + "," + valArray.getString(i);
Log.i("p",p);
}
} finally {
is.close();
}
}
private String readAll(BufferedReader rd) throws IOException {
// TODO Auto-generated method stub
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}}
But I am getting the source of the file in the jsonText String.And as it does not start with a '{' i am getting following error in the log :
org.json.JSONException: A JSONObject text must begin with '{' at character 1>
Looks to me like the issue is with the page you have created to return the response. Is there a particular reason you are using an HTML page with frames? If you browse the page loaded in the frame (http://88.198.1.116:9080/parentconnect/services/student/getStudentDetails?studentid=1&schoolid=1) you will see that the source has the JSON string you are after.
Why are you not browsing to this URL instead of the HTML page?
Based on the fact that the string does not start with a '{' character I would say the json you have is actually invalid and malformed json. Take a look here and here.
I would say your options are to see if you can get the malformed json fixed on the server side, or else on the client do some checks to see if it's malformed and try to fix it before passing the string to the jsonObject parsers.
I have an app in which I parse a .txt file from a URL and spit out the string to the user. I want to remove the first 16 characters of the string. How can I do this?
EDIT- I want to remove 16 characters from the data I receive from my http call.
public void onClick(View src) {
switch(src.getId()) {
case R.id.buttonRetrieveMetar:
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(EditTextAirportCode.getWindowToken(), 0);
textDisplayMetar.setText ("");
airportcode = EditTextAirportCode.getText().toString();
url = urlmetar + airportcode + ".TXT";
//Added 06-27-11 METAR code
textDisplayMetar.setText ("");
try {
HttpGet httpGet = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
// Execute HTTP Get Request
HttpResponse response = httpclient.execute(httpGet);
content = response.getEntity().getContent();
BufferedReader r = new BufferedReader(new
InputStreamReader(content));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line);
}
textDisplayMetar.append("\n" + total + "\n");
} catch (Exception e) {
//handle the exception !
}
break;
Thanks!
You can't modify the string itself, but you can create a substring easily enough:
line = line.substring(16);
The single-parameter overload of substring takes the whole of the rest of the string after the given start index. The two-parameter overload starts at an index specified by the first argument, and ends at an index specified by the second argument (exclusive). So to get the first three characters after "skipping" the first 16, you'd use:
line = line.substring(16, 19);
Note that you don't have to assign back to the same variable - but you need to understand that it doesn't affect the string object that you call it on. So:
String original = "hello world";
String secondPart = original.substring(6);
System.out.println(original); // Still prints hello world
System.out.println(secondPart); // Prints world
EDIT: If you want to remove the first 16 characters of the whole file, you want:
textDisplayMetar.append("\n" + total.toString().substring(16) + "\n");
If you want that on a per-line basis, you want:
while ((line = r.readLine()) != null) {
total.append(line.substring(16));
}
Note that both of these may require extra validation - if you call substring(16) on a string with less than 16 characters, it will throw an exception.
Try this:
String newString = oldString.substring(16);