I am trying to figuring out about REST method. I watched few videos from google conference about REST technology but what I saw was app's implementation of connectivity with database. So I would like to know if my code would count as a REST.
PHP code:
<?php
mysql_connect("localhost","*****","********");
mysql_select_db("********");
$cname = mysql_real_escape_string($_REQUEST['cname']);
$q=mysql_query("SELECT mdl_course_sections.summary FROM mdl_course, mdl_course_sections WHERE mdl_course.id = mdl_course_sections.course AND mdl_course.fullname = '$cname' AND mdl_course_sections.section > 0");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
JAVA code:
public class CourseSegmentsActivity extends ListActivity{
String courseName = null;
String segmentName = null;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Intent i = getIntent();
courseName = i.getStringExtra("courseName");
ArrayList<HashMap<String,String>> myCoursesList = new ArrayList<HashMap<String,String>>();
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("cname",""+courseName));
InputStream is = null;
String result = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("****************");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-10"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try{
JSONArray jArray = new JSONArray(result);
for(int ii=0;ii<jArray.length();ii++){
JSONObject json_data = jArray.getJSONObject(ii);
segmentName = json_data.getString("summary");
HashMap<String,String> map = new HashMap<String, String>();
map.put("summary", segmentName);
myCoursesList.add(map);
}
} catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, myCoursesList,R.layout.course_segments_list_layout,
new String[] {"summary"}, new int[] { R.id.name});
setListAdapter(adapter);
}
}
If not what I am missing?
No, you are NOT. if you follow REST standards, you should be using http protocol efficiently. As per REST standard,
if you are reading data - use GET
if you are reading meta-data - use HEAD
if you are writing data - use POST
if you are modifying data - use PUT
if you are deleting - use DELETE,
please refer to the w3c specification of http protocol(RFC2616) for further info.
No, you are using POST to retrieve data. However, POST is meant to be used to edit existing data.
Query strings are also rather unlikely when using REST - usually you use the URL to specify resources
Have a look at http://en.wikipedia.org/wiki/REST#RESTful_web_services
Related
I use this code below, it works perfectly in Android 2.3.3. However, in 4.0+ it can't connect to database somehow. I saw some posts about you need to get it in a asynch class. I also tried that, but I can't seems it to work. I probably use it wrong, but it is hard for me to understand.
public class connector extends Activity {
/** Called when the activity is first created. */
TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getServerData(null);
}
//i use my real ip here
public String getServerData(String returnString) {
System.out.println("going to connector class");
InputStream is = null;
final String KEY_121 = "http://10.0.0.128/connector.php";
String result = "";
//the year data to send
// ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// nameValuePairs.add(new BasicNameValuePair("year","1970"));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
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("ID")+
", \nActara: "+json_data.getString("Actara")
);
//Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return returnString;
}
}
Logcat error (on 4.0+):
11-12 12:02:35.658: E/log_tag(14083): Error in http connection android.os.NetworkOnMainThreadException
11-12 12:02:35.658: E/log_tag(14083): Error converting result java.lang.NullPointerException
11-12 12:02:35.663: E/log_tag(14083): Error parsing data org.json.JSONException: End of input at character 0 of
Only the first error line is important, because it can't connect to a database, it gives a nullPointer (2nd and 3rd error).
This is what I tried in Asynch:
public class connector extends Activity {
/** Called when the activity is first created. */
TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new BackgroundAsyncTask().execute();
}
public class BackgroundAsyncTask extends
AsyncTask<Void, Integer, Void> {
InputStream is = null;
final String KEY_121 = "http://10.0.0.128/connector.php";
String result = "";
String returnString = "";
protected void onPostExecute(Void result) {
}
#Override
protected void onPreExecute() {
System.out.println("onPreExecute");
}
protected Void doInBackground(String... params) {
try{
System.out.println("background in progress");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
// httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
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("ID")+
", \nActara: "+json_data.getString("Actara")
);
//Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return null;
}
protected void onProgressUpdate(Integer... values) {
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
return null;
}
}
}
Someone that can help me? I don't know for sure what the real cause is why it isn't working for 4.0+.
If you need more info, just say it, and I will post it.
Code can be a bit messy, I didn't really "clean" it up yet properly.
Since Android 3.0 you are not allowed to do network stuff on the main thread. Why? because network problems will lead to a slow ui. So you have to do all the http stuff in a new thread. You are on the right path but you made a mistake in your AsyncTask. Delete the empty doInBackground method in you async task and write #Override over your method.
android.os.NetworkOnMainThreadException
this eror comes With HoneyComb(3.0 or Later). you can not perform a networking operation on its main thread as documentation says. to getting ride of this you must use handler or asynctask. AFAIK There is no another way to do it.
you can See this for More Details WHY ICS Crashes your App
Try Using Below Code Snippet
new Thread(){
public void run(){
//do your Code Here
}
}.start();
Ok right...
After searching for few hours, making this question, then 10 minutes later, you find a solution...
Option 1:
I added this line:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
But I reccomend NOT to use option 1, this is a bad solution for real. Use option 2!
//===========================================================================
Option 2:
Used this tutorial to make a proper ASyncTask: http://www.elvenware.com/charlie/development/android/SimpleHttpGetThread.html
//===========================================================================
Used ASyncTask as final (option 2).
why you are passing null in function of web connection and web service .?
getServerData(null);
So as the title suggest my problem is getting a response to a HTTP POST I'm making.
What SHOULD be happening is I send a bunch of variables, the PHP checks the database for them and sends back to me the result (as an echo to the page).
Here is the android code:
public class CheckChallenge extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urls)
{
String response = "";
try
{
URL = urls[0];
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("victim",NetPlay.myId));
// need to return these to an array
nameValuePairs.add(new BasicNameValuePair("rival",rivalid));
nameValuePairs.add(new BasicNameValuePair("word","null"));
nameValuePairs.add(new BasicNameValuePair("won","0"));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://www.hanged.comli.com/check-rival.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse execute = httpclient.execute(httppost);
HttpEntity entity = execute.getEntity();
//InputStream is = entity.getContent();
//mText.setText(is.toString());
Log.i("postData", execute.getStatusLine().toString());
//HttpEntity entity = response.getEntity();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection"+e.toString());
}
return response;
}
#Override
protected void onPostExecute(String result)
{
// CHECK ENTIRE DATABASE FOR MY ID //
// IF MY ID IS THERE THEN THAT MEANS IVE CHALLENGED SOMEONE //
}
}
Here is the PHP which I think is ok just including this for completeness:
$connect = mysql_connect("$mysql_host", "$mysql_user", "$mysql_password")or die("cannot connect");
mysql_select_db("$mysql_database", $connect)or die("cannot select DB");
session_start();
$victim = $_POST['victim'];
$rival = $_POST['rival'];
$word = $_POST['word'];
$won = $_POST['won'];
$query = "SELECT rival FROM currentgames";
$result = mysql_query($query);
if (!$result)
{
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0)
{
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result))
{
echo $row["rival"];
}
Any help with this would be very appreciated, trying to get my head around all this HTTP POSTing stuff.
Example of sending an HTTP request and reading back the HTTP response:
String res = "";
String url = "http://www.domain.com/youscript.php";
URL urlObj = new URL(url);
URLConnection lu = urlObj.openConnection();
// Send data - if you don't need to send data
// ignore this section and just move on to the next one
String data = URLEncoder.encode("yourdata", "UTF-8");
lu.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(lu.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(lu.getInputStream()));
String line = "", res = "";
while ((line = rd.readLine()) != null) {
res += line;
}
wr.flush();
wr.close();
System.out.println(res);
I've been using the coding from an example from this link: The code is as shown below:
public class food extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String result = null;
InputStream is = null;
StringBuilder sb=null;
String result=null;
TextView fdi = (TextView)findViewById(R.id.textView1);
TextView fdn = (TextView)findViewById(R.id.textView2);
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://127.0.0.1/food.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//paring data
int fd_id;
String fd_name;
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
fd_id=json_data.getInt("FOOD_ID");
fd_name=json_data.getString("FOOD_NAME");
}
}catch(JSONException e1){
Toast.makeText(getBaseContext(), "No Food Found", Toast.LENGTH_LONG).show();
}catch (ParseException e1){
e1.printStackTrace();
}
}
}
Now my question is how to pass this data to a list view, like for each iteration a list item must be added with the retrieved data.
Please help me
Thanks in advance
You are already getting strings in below code, Why don't you use that.
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
fd_id=json_data.getInt("FOOD_ID");
fd_name=json_data.getString("FOOD_NAME");
}
//fdname and fd_id you are getting it right,
If your code is not working then add what problem you are facing.
according to your response/result from the server below code is working for me and giving output in string ,
try {
String response ="[{\"FOOD_ID\":\"1\",\"FOOD_NAME\":\"Rice\"},{\"FOOD_ID\":\"2\",\"FOOD_NAME\":\"Daal\"}] ";
JSONArray array;
array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(0);
String id_fd = obj.getString("FOOD_ID");
String name_fd = obj.getString("FOOD_NAME");
Log.d("JSONArray", id_fd+" " +name_fd);
}} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
please use it according to your need.
The root cause of the error a NullPointerException. This means that you are trying to use an object that has the value null. Usually this is because the object has not yet been initialised.
In your case the nullpointer is caused by something at line 29 of your Food class, probably one of these two lines
TextView fdi = (TextView)findViewById(R.id.textView1);
TextView fdn = (TextView)findViewById(R.id.textView2);
Are you sure that both the R.id.textView1 and R.id.textView1 exist? They should be specified somewhere in a layout xml file, something like this:
<TextView
android:id="#+id/textView1"
....
I want to receive from an MySQL-Server all my data from a table.
So, I wrote a PHP script that fetches the complete table and encode it to JSON format.
PHP-Code:
<?php
include ("connect.php");
mysql_query("SET NAMES 'utf8'");
$query = mysql_query('SELECT * FROM MyTable);
while ($row = mysql_fetch_assoc($query))
{
$buffer[] = $row;
}
print json_encode( $buffer );
mysql_close($dbconnect);
?>
So, when I run the script, all the JSON String looks fine, no corupted characters etc.
In Android App:
When I run the following codes and receive the JSON String throught the HTTP, I get a strange String in the Debugger...
Screenshot: http://goo.gl/gTssQ
Java Code:
String result = "";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
// HTTP Verbindung
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mywebsite.com");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e)
{
Log.e("log_tag", "Fehler bei der http Verbindung "+e.toString());
}
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
try
{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
);
}
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
}
I cant understand the Problem, because my Database is full UTF-8 and my script too.
I hope someone can help me! :-)
Greets, andr3w
So I've used code examples from all over the net and got my app to accurately call a .php file on my server, retrieve the JSON data, then parse the data, and print it.
The problem is that its just printing to the screen for sake of the tutorial I was following, but now I need to use that data in other places and need help figuring out that process.
The ultimate goal is to return my db query with map coordinates, then plot them on a google map. I have another app in which I manually plot points on a map, so I'll be integrating this app with that once I can get my head around how to correctly manipulate the data returned.
public class Remote extends Activity {
/** Called when the activity is first created. */
TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create a crude view - this should really be set via the layout resources
// but since its an example saves declaring them in the XML.
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
// Set the text and call the connect function.
txt.setText("Connecting...");
//call the method to run the data retreival
txt.setText(getServerData(KEY_121));
}
public static final String KEY_121 = "http://example.com/mydbcall.php";
private String getServerData(String returnString) {
InputStream is = null;
String result = "";
//the year data to send
//ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//nameValuePairs.add(new BasicNameValuePair("year","1970"));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","longitude: "+json_data.getDouble("longitude")+
", latitude: "+json_data.getDouble("latitude")
);
//Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return returnString;
}
}
So the code:
returnString += "\n\t" + jArray.getJSONObject(i);
is what is currently printing to the screen.
What I have to figure out is how to get the data into something I can reference in other spots in the program, and access the individual elements
ie:
double longitude = jArray.getJSONObject(3).longitude;
or something to that effect..
I figure the class getServerData will have to return a Array type or something?
Any help is appreciated, thanks.
First of all, you should not be making server calls on the UI thread. Use AsyncTask, or a Service to make remote calls on a separate thread.
Next, I don't know the exact structure of your returned Json, but it sounds like you want to convert it into a cleaner object model. Just create an object that has a field for each entry in your Json array, and replace your log statements with assignment statements. I.e:
class Location {
private double latitude;
private double longitude;
public Location(double latitude, double longitude) { ....}
}
private List<Location> getServerData(String returnString) {
List<Location> result = new ArrayList<Location>();
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
Location loc = new Location(json_data.getDouble("latitude"), json_data.getDouble("longitude"));
result.add(loc);
}
return result;
}