the variable from php won't show up on android (using json) - java

I'm trying to make an android app using fuzzy (have yet to make the whole fuzzy calculation) so the calculations will be done in php. For starter I was just making a simple calculation in php first and trying to send to the android. but it doesn't show anything..there no error either.
Here's the simple example of my php code calc.php
<?php
$calcresult = 56 * 100 * 2051 / 49;
echo json_encode($calcresult);
?>
and this is my java code JSONActivity.class
package com.example.ta2;
import java.io.BufferedReader;
import java.io.InputStream;import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class AturanKonsumsi extends Activity {
private JSONObject jObject;
private String xResult ="";
private String url = "http://10.0.2.2/calc.php";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.daftarmakanan);
TextView txtResult = (TextView)findViewById(R.id.TextViewResult);
xResult = getRequest(url);
try {
parse(txtResult);
} catch (Exception e) {
e.printStackTrace();
}
}
private void parse(TextView txtResult) throws Exception {
jObject = new JSONObject(xResult);
JSONArray menuitemArray = jObject.getJSONArray("calcresult");
String sret="";
for (int i = 0; i < menuitemArray.length(); i++) {
System.out.println(menuitemArray.getJSONObject(i)
.getString("calcresult").toString());
sret +=menuitemArray.getJSONObject(i).getString(
"calcresult").toString()+"\n";
}
txtResult.setText(sret);
}
public String getRequest(String Url){
String sret="";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(Url);
try{
HttpResponse response = client.execute(request);
sret =request(response);
}catch(Exception ex){
Toast.makeText(this,"Gagal "+sret, Toast.LENGTH_SHORT).show();
}
return sret;
}
public static String request(HttpResponse response){
String result = "";
try{
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
result = str.toString();
}catch(Exception ex){
result = "Error";
}
return result;
}
}
when I run the android app it doesn't show the value in $calcresult and there's no error either. thanks for your help

calcresult is not referenced by the json your php script is producing. Check the output. To make your java code work, you'll need to create the json like so:
<?php
$calcresult = 56 * 100 * 2051 / 49;
$json = array( 'calcresult' => array( $calcresult ) );
echo json_encode($json);
?>
Alternately, you can simplify your java.

Related

My android studio app keeps crashing after using a background method to read a json from my fragment

I am making an app using the Kitsu API. Here in this moment I have a fragment that allows me to search different anime using the api to get information such as name, synopsis, etc. After parsing the information I proceed to go back to my main activity to pass it to my new fragment, but it crashes the moment I initialize the method to go back to my main activity. My question is how do I use a fragment to read a JSON with a background class using ASYNCTASK and display it in a new fragment?
I have noticed that it jumps around a lot from my fragment, in an activity different from my main, to a class running in the background, to my main, to my fragment. Below are images of my code. Thank you very much.
Search fragment code, Main Activity search related methods, Search results background tasks, Search Results Fragment. To clarify It stops before I get to the string I labeled crashpoint and doesn't make it to the search results fragment. I felt like it would be handy to have that bit of code in there. Here is the error I get with my code when I run it.
You don't need to create a new fragment after reading JSON. Just to post an simple code that read JSON with async task:
package com.example.compsci_734t;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.zip.GZIPInputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class People extends Activity{
ArrayList<String> items = new ArrayList<String>();
static InputStream is = null;
//private static String url = "";
//private static String url = "http:...";
private static String url = "http....";
//URL requestUrl = new URL(url);
JSONArray people = null;
private static final String TAG_COURSES = "Courses";
static JSONObject jObj = null;
static String json = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.people);
new MyTasks().execute();
}
private class MyTasks extends AsyncTask<URL, Void, JSONObject> {
#Override
protected JSONObject doInBackground(URL... urls) {
// return loadJSON(url);
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
//HttpPost httpPost = new HttpPost(url);
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
/*BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);*/
InputStream inputStream = is;
GZIPInputStream input = new GZIPInputStream(inputStream);
InputStreamReader reader = new InputStreamReader(input);
BufferedReader in = new BufferedReader(reader);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = in.readLine()) != null) {
sb.append(line);
//System.out.println(line);
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
JSONArray people = new JSONArray(json);
//JSONArray people = new JSONArray(json);
for (int i = 0; i < people.length(); i++) {
//System.out.println(courses.getJSONObject(i).toString());
JSONObject p = people.getJSONObject(i);
// Storing each json item in variable
String person_id = p.getString("someString1");
items.add(person_id);
/*Log.v("--", "People: \n" + "\n UPI: " + person_id);*/
}
//jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
protected void onPostExecute(JSONObject json) {
ListView myListView = (ListView)findViewById(R.id.peopleList);
myListView.setAdapter(new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, items));
}
}
The sample code was taken from this answer.

Extracting Values Not Working JSON file?

I am newbie in java programming. I am trying to get Instagram users full name. and below is my code
package gibs.smith.testapp;
import android.os.AsyncTask;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class fetchData extends AsyncTask<Void,Void,Void> {
private String name = "";
private String link ="";
#Override
protected Void doInBackground(Void... voids) {
try {
URL url= new URL("https://instagram.com/priya.p.varrier/?__a=1");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line !=null){
line =bufferedReader.readLine();
JSONObject jo= new JSONObject(line);
JSONObject user=jo.getJSONObject("user");
name=user.getString("full_name");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.data.setText(this.name);
}
}
but it is not working. it dose not extracts the string value "full_name".
It is retrieving the JSON file but not the desired value.
The URL is https://instagram.com/priya.p.varrier/?__a=1
any help would be great.
----Edit-----
adding graphql object causes app crash and below is catlog output
here is the log
https://justpaste.it/1itsa
First the bug. It must be NullPointerException.
while (line !=null)
it will run until line = null. Then this line will give you the exception.
new JSONObject(line);
and you shoud get the graphql first.
so the solution should look like this.
if(line != null) {
JSONObject jo = new JSONObject(line);
JSONObject graphql = jo.getJSONObject("graphql");
JSONObject user = graphql.getJSONObject("user");
name = user.getString("full_name");
}
As per your JSON
your full_name key is inside user JSONObject which is inside graphql JSONObject.
So to get the full_name value you have to first retrieve graphql JSONObject.
JSONObject jo = new JSONObject(line);
JSONObject graphqlObj = jo.getJSONObject("graphql");
JSONObject user = jographqlObj.getJSONObject("user");
name=user.getString("full_name");
You can use http://jsonviewer.stack.hu/ to check JSON structure of your file.

Invoke a method of a web service from a Java (Android) external app

sorry if the question is too easy, but I do not know the answer..
What I have to do is to invoke a method of a web service using a java app.
Here you can find a web service:
http://muovi.roma.it/ws/xml/autenticazione/1
And I want Invoke the method called "autenticazione.Accedi:"
I have a python example that is doing this:
from xmlrpclib import Server
from pprint import pprint
DEV_KEY = 'Inserisci qui la tua chiave'
s1 = Server('http://muovi.roma.it/ws/xml/autenticazione/1')
s2 = Server('http://muovi.roma.it/ws/xml/paline/7')
token = s1.autenticazione.Accedi(DEV_KEY, '')
res = s2.paline.Previsioni(token, '70101', 'it')
pprint(res)
But I need the same operation in Java... Can anyone help me in this problem?
thank you
I recommend you using this project as a Library.
https://github.com/matessoftwaresolutions/AndroidHttpRestService
It makes you easy deal with apis, control network problems etc.
You can find a sample of use there.
You only have to:
Build your URL
Tell the component to execute in POST/GET etc. mode
Build your JSON
I hope it helps!!!
package com.example.jojo.gridview;
import android.util.Log;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
/**
* Created by jojo on 12/10/15.
*/
public class WebService {
String url="http://192.168.1.15/Travel_Dairy/";
String invokeGetWebservice(String webUrl)
{
String result = "";
webUrl=webUrl.replace(" ","%20");
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(webUrl);
HttpResponse response;
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputstream= entity.getContent();
BufferedReader bufferedreader = new BufferedReader(
new InputStreamReader(inputstream), 2 * 1024);
StringBuilder stringbuilder = new StringBuilder();
String currentline = null;
try {
while ((currentline = bufferedreader.readLine()) != null) {
stringbuilder.append(currentline + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
result = stringbuilder.toString();
Log.e("Result", result);
inputstream.close();
return result;
}
} catch (ClientProtocolException e1) {
Log.e("ClientProtocolException", e1.toString());
return result;
} catch (IOException e1) {
Log.e("IOException", e1.toString());
return result;
}
return result;
}
public List<DataModel> getTrips() {
String getname="view_details.php?";
String completeurlforget=url+getname;
//String seturl= "ur_id="+userid;
//String finalurl=completeurlforget+seturl;
String result=invokeGetWebservice(completeurlforget);
try {
JSONArray jsonarry=new JSONArray(result);
List<DataModel> ar=new ArrayList();
for(int i=0;i<jsonarry.length();i++)
{
JSONObject jsonobj=jsonarry.getJSONObject(i);
DataModel user=new DataModel();
user.setName(jsonobj.getString("name"));
user.setImage(jsonobj.getString("image"));
ar.add(user);
}
return ar;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}

Webpage login error-Android App

I'm new to Android and Java. I'm creating an app to login to my ISP. This is the page: http://reliancebroadband.co.in/reliance/login.do
Earlier, I was using a python script, which worked flawlessly. Its like this:
#!/usr/bin/env python
# encoding: utf-8
import urllib2, urllib, cookielib
username = 'my-username'
password = 'my-password'
jar = cookielib.FileCookieJar("cookies")
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar))
response = opener.open("http://reliancebroadband.co.in/reliance/startportal_isg.do")
login_data = urllib.urlencode({'userId' : username, 'password' : password, 'action' : 'doLoginSubmit'})
resp = opener.open('http://reliancebroadband.co.in/reliance/login.do', login_data)
And now i'm trying to create an android app(source: http://www.compiletimeerror.com/2013/01/login-application-for-android.html#.U7AFBPmSz9Y) (Tried contacting the developer there, but he's not responding.)
The app is compiling correctly, but while tring to login, its just returning the source code of the login page in the error dialogue, instead of logging in.
Here's the code:
MainActivity.java:
package com.app.reliancebblogin;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
#SuppressLint("NewApi")
public class MainActivity extends Activity
{
EditText un, pw;
TextView error;
Button ok;
private String resp;
private String errorMsg;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
un = (EditText) findViewById(R.id.et_un);
pw = (EditText) findViewById(R.id.et_pw);
ok = (Button) findViewById(R.id.btn_login);
error = (TextView) findViewById(R.id.tv_error);
ok.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
/** According with the new StrictGuard policy, running long tasks on the Main UI thread is not possible
So creating new thread to create and execute http operations */
new Thread(new Runnable()
{
#Override
public void run()
{
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username",un.getText().toString()));
postParameters.add(new BasicNameValuePair("password",pw.getText().toString()));
String response = null;
try
{
response = SimpleHttpClient.executeHttpPost("http://reliancebroadband.co.in/reliance/login.do", postParameters);
String res = response.toString();
resp = res.replaceAll("\\s+", "");
}
catch (Exception e)
{
e.printStackTrace();
errorMsg = e.getMessage();
}
}
}).start();
try
{
/** wait a second to get response from server */
Thread.sleep(1000);
/** Inside the new thread we cannot update the main thread
So updating the main thread outside the new thread */
error.setText(resp);
if (null != errorMsg && !errorMsg.isEmpty())
{
error.setText(errorMsg);
}
}
catch (Exception e)
{
error.setText(e.getMessage());
}
}
});
}
}
SimpleHttpClient.java:
package com.app.reliancebblogin;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public class SimpleHttpClient
{
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/**
* Get our single instance of our HttpClient object.
*
* #return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient()
{
if (mHttpClient == null)
{
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
/**
* Performs an HTTP Post request to the specified url with the
* specified parameters.
*
* #param url The web address to post the request to
* #param postParameters The parameters to send via the request
* #return The result of the request
* #throws Exception
*/
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception
{
BufferedReader in = null;
try
{
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null)
{
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally
{
if (in != null)
{
try
{
in.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
/**
* Performs an HTTP GET request to the specified url.
*
* #param url The web address to post the request to
* #return The result of the request
* #throws Exception
*/
public static String executeHttpGet(String url) throws Exception
{
BufferedReader in = null;
try
{
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null)
{
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally
{
if (in != null)
{
try
{
in.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}

I am getting Error parsing data org.json.JSONException

I am getting this error in my LogCat:
Error parsing data org.json.JSONException: Value  of type java.lang.String cannot be converted to JSONArray
Below are every file I could show you! Please let me know the problem and its solution ASAP. What I guess is:
1. Maybe the is problem is with parsing data in JSON array.
2. Maybe the problem is with my php api, I think I am not properly encoding the json_encode because it gives me RAW JSON, like every thing in one line.
as below
[{"uid":"120","name":"MyFirstName MyLastName"}]
Please also let me know, their is some difference in working of both format, 1. Raw JSON and 2. Intented Json
below is the intented json format
[
{
"uid":"120",
"name":"MyFirstName MyLastName"
}
]
Here is the JSONUseActivity.java
package com.example.oncemore;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import com.example.oncemore.CustomHttpClient;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class JSONUseActivity extends Activity {
EditText email,password;
Button submit;
TextView tv; // TextView to show the result of MySQL query
String returnString; // to store the result of MySQL query after decoding
// JSON
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is
// most commonly
// used to catch
// accidental
// disk or
// network
// access on the
// application's
// main thread
.penaltyLog().build());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jsonuse);
email = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.password);
submit = (Button) findViewById(R.id.submitbutton);
tv = (TextView) findViewById(R.id.showresult);
// define the action when user clicks on submit button
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// declare parameters that are passed to PHP script i.e. the
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
// define the parameter
postParameters.add(new BasicNameValuePair("email",email.getText().toString()));
postParameters.add(new BasicNameValuePair("password",password.getText().toString()));
String response = null;
// call executeHttpPost method passing necessary parameters
try {
response = CustomHttpClient.executeHttpPost(
"http://mywebsite.com/android/api.php",
postParameters);
// store the result returned by PHP script that runs MySQL
// query
String result = response.toString();
// parse json data
try {
returnString = "";
//I think the line below is creating some problem
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag",
"id: " + json_data.getInt("uid")+", name: " + json_data.getString("name"));
// Get an output to the screen
returnString += "\n" + json_data.getString("name")
+ " -> " + json_data.getInt("uid");
}
}catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
try {
tv.setText(returnString);
}
catch (Exception e) {
Log.e("log_tag", "Error in Display!" + e.toString());
;
}
}
catch (Exception e) {
Log.e("log_tag",
"Error in http connection!!" + e.toString());
}
}
});
}
}
Here is the CustomHttpClient.java
package com.example.oncemore;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import android.util.Log;
public class CustomHttpClient {
/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;
/**
* Get our single instance of our HttpClient object.
*
* #return an HttpClient object with connection parameters set
*/
private static HttpClient getHttpClient() {
if (mHttpClient == null) {
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
/**
* Performs an HTTP Post request to the specified url with the specified
* parameters.
*
* #param url
* The web address to post the request to
* #param postParameters
* The parameters to send via the request
* #return The result of the request
* #throws Exception
*/
public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
Log.e("log_tag", "Error converting result "+e.toString());
e.printStackTrace();
}
}
}
}
/**
* Performs an HTTP GET request to the specified url.
*
* #param url
* The web address to post the request to
* #return The result of the request
* #throws Exception
*/
public static String executeHttpGet(String url) throws Exception {
BufferedReader in = null;
try {
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity()
.getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
Log.e("log_tag", "Error converting result "+e.toString());
e.printStackTrace();
}
}
}
}
}
Here is the api.php
<?php
require_once("../contactdb.php");
$myusername=$_REQUEST["email"];
$mypassword=$_REQUEST["password"];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT uid,name FROM u_info WHERE email='".$myusername."' AND password ='".$mypassword."'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
if($count==1){
while($row=mysql_fetch_assoc($result))
$output[]=$row;
echo json_encode($output);
mysql_close();
}else{
echo "Error Occured!";
}
?>
Finally, When I goto browser and write like this
http://mywebsite.com/android/api.php?email=myname#yahoo.com&password=1234
I got this json array!
[{"uid":"120","name":"MyFirstName MyLastName"}]
So Far I google, I have found different formats of json array! I found everywhere Intented Json. My json array is currently in Raw Json format. I don't find anywhere how to convert Raw Json format into Intented Json format.
Thanks in advance guys!
Any help would be appreciated! If possible, please provide the correct code!
That is NOT valid JSON syntax:
{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}
Is Valid.
Note: This is also valid:
{"employees": [ { "firstName":"John" , "lastName":"Doe" }, { "firstName":"Anna" , "lastName":"Smith" }, { "firstName":"Peter" , "lastName":"Jones" } ] }
The syntax structure is the important part, not the formatting in terms of indentation.
As otherwise said, to use the fomat you're returning, you need to cut the substring from the response, i.e get rid of the square brackets surrounding the braces.
In PHP I create a proper json response as follows:
// array for JSON response
$response = array();
$response["apps"] = array();
$apps = array();
$apps["name"] = $row["name"];
$apps["package"] = $row["package"];
$apps["version"] = $row["version"];
$apps["dateversion"] = $row["dateversion"];
array_push($response["apps"], $apps);
$response["success"] = 1;
echo json_encode($response);
This basically gives
{ "success":"1", "apps":{["name":"NAME", "package":"PACKAGE", "version":"VERSION", "dateversion":"DATEVERSION"]}}
which can be parsed correctly by any of the abundant examples of JSON classes which you can make use of. Hacking and using substring to manually remove the first N characters is NOT good practice...

Categories

Resources