I am trying to read a database in my from a remote DB, for that i am using a php code to connect to my Mysql DB and to query my DB:
Name of the file: check.php:
<?php
require_once("php/dbconnect.php");
$query = "SELECT name FROM user ";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
while ( $row = mysql_fetch_array( $result ) ) {
$output[]=$row['name'];
}
print(json_encode($output));
mysql_close();
?/>
And the Java (Android) code to connect to the remote DB:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
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.util.Log;
import android.widget.Toast;
import java.net.URI;
public class ConnectToMyDb extends Activity {
InputStream is;
private HttpPost httppost;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String result = "";
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://www.Myurl.com/check.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("log_tag", "connection success ");
Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
Toast.makeText(getApplicationContext(), "fail", Toast.LENGTH_SHORT).show();
}
//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");
Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
Toast.makeText(getApplicationContext(), "fail", Toast.LENGTH_SHORT).show();
}
//parse json data
try{
//ArrayList<Messages> result1 = new ArrayList<Messages>();
JSONArray jArray = new JSONArray(result);
JSONObject json_data= new JSONObject(result);
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
Log.i("log_tag"," name: "+json_data.getString("name");
Toast.makeText(getApplicationContext(), "pass", Toast.LENGTH_SHORT).show();
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
Toast.makeText(getApplicationContext(), "fail", Toast.LENGTH_SHORT).show();
}
}
My problem its not the connection but the parsing of the json i get an exception:
Error parsing data org.json.JSONException:
Value <!DOCTYPE of type java.lang.String cannot be converted to JSONArray
I would get rid of this line:
JSONArray jArray = new JSONArray(result);
and do this instead:
JSONObject json_data = new JSONObject(result);
JSONArray nameArray = json_data.names();
JSONArray valArray = json.toJSONArray(nameArray);
I believe this is correct, nonetheless, please study this tutorial, it will work for you:
Android as a Restful Client
It looks like the string that you are trying to convert to JSON (i.e. result) is actually a full HTTP response. In order for your code to pass, you'll need just the raw JSON, excluding the HTML.
Related
I can't figure out whats wrong with this code , it's supposed to get data from php page that i created.
I'm using Eclipse with android SDK.
package com.myproject.myproject2;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
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.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class EntList extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.entlist);
JSONArray jsonArray = null;
String jsonString = null;
StringBuilder stringBuilder = null;
InputStream inStream = null;
TextView tv = (TextView) findViewById(R.id.listtitle);
ArrayList<NameValuePair> nVPArray = new ArrayList<NameValuePair>(); //This is empty because you're asking for data
try{
//Connect to your script, and save get an object to read the data (inStream)
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://sawtaljabal.com/ar/android_connect/test.php"); // Be sure to replace with your actual script
post.setEntity(new UrlEncodedFormEntity(nVPArray));
HttpResponse postResponse = client.execute(post);
HttpEntity responseEntity = postResponse.getEntity();
inStream = responseEntity.getContent();
}catch(Exception e){
Log.e("Error connecting", e.getLocalizedMessage());
}
try{
//read the stream to a single JSON string
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream,"iso-8859-1"), 10); // iso-8859-1 is the character converter
stringBuilder = new StringBuilder();
stringBuilder.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
inStream.close();
jsonString = stringBuilder.toString();
}catch(Exception e){
Log.e("Error creating JSON string", e.getLocalizedMessage());
}
try{
//Turn the JSON string into an array of JSON objects
jsonArray = new JSONArray(jsonString);
JSONObject jsonObject = null;
for(int i=0;i< jsonArray.length();i++){
jsonObject = jsonArray.getJSONObject(i);
//do something with the object, like String data = jsonObject.getString("KEY");
String data = jsonObject.getString("n_t");
tv.setText(data);
}
}
catch(JSONException e){
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
}
I don't even know what to try , can u help me please, this is my first Application.
To connect php using Android
first your have to call a web service (which may be a php page returning json), call to this page should be in AsynTask class.
Then you need to parse json in right way.
You can try any good tutorial for this. Try this
If this is your first android app you may want to try cloning this project and learn with code there:
https://github.com/jgilfelt/android-jsonarrayadapter?files=1
Hope it helps.
Are you sure, the String you are getting in the response is a JSON Array. I think it should be a JSON object by which you can get the further JSON Array .
which means
// try parse the string to a JSON object
try {
jObj = new JSONObject(jsonString);
} catch (JSONException e) {
}
and then parse the JSON array from JSON Object.
Check Out this link, it might be helpful.
Also do all networking call in AsynTask or in a different thread.
I am trying to access the json that displays the contents of my android application. The FileNotFound exception is throwing in Android 4.0.4 but the json can be accessed in Android 2.3.3. The json can also be accessed from browser using the same url. What is wrong in the code ? Can anyone help me regarding this issue.
I am using the code below:
url = new URL("http://www.dynamiskdesign.se/ipromotionnew/json/148.json");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
InputStream input = httpURLConnection.getInputStream();
if (input != null) {
writer = new StringWriter();
char[] buffer = new char[1024];
Reader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
input.close();
}
String jsontext = writer.toString();
This is because the combination of network and threads.
Explanation is also on that page (link).
I had this too, look at this answer:
httpclient (phpmyadmin) not working on Android 4.0+
I think this solution can work:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
//
public class Connector extends AsyncTask<TextView, Void, String> {
#Override
protected String doInBackground(TextView... params) {
// TODO Auto-generated method stub
return GetSomething();
}
private final String getSomething() {
try{
url=new URL("http://www.dynamiskdesign.se/ipromotionnew/json/148.json");
HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
InputStream input=httpURLConnection.getInputStream();
} catch(Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
//convert response to string
try{
if (input != null)
{
writer = new StringWriter();
char[] buffer = new char[1024];
Reader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
input.close();
}
} catch(Exception e) {
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try {
String jsontext = writer.toString();
} catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
return returnString;
}
protected void onPostExecute(String page) {
//onPostExecute
}
}
I've been going through two tutorials to get the code for this project of mine;
Connecting to MySQL database
Connecting Android to remote mysql via PHP and JSON
I've learnt the code up to a point since I'm still a beginner and used a lot of it at the same time. Here is what I have at the moment:
package com.android.history;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
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.HttpPost;
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.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class CurrentSeasonDrivers extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.currentseason_drivers);
}
//PARSE JSON ETC
public void parseJSON() {
String result = "";
String drivername = "";
String drivesfor = "";
InputStream is=null;
//HTTP POST REQUEST
try{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.0.13/testdatabase.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());
Toast.makeText(getBaseContext(), "Could not connect", Toast.LENGTH_LONG).show();
}
//CONVERT DATA 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());
Toast.makeText(getBaseContext(), "Could not convert result", Toast.LENGTH_LONG).show();
}
//PARSE JSON DATA
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
drivername=json_data.getString("Driver_full_name");
drivesfor=json_data.getString("Drives_for");
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
Toast.makeText(getBaseContext(), "Could not parse data", Toast.LENGTH_LONG).show();
}
}
}
Now I have no errors and the application works fine. When I got to the page that this is all made for I get nothing. A blank page. As you can see from my code I've added toasts exceptions but none of them show up either. Even if I intentionally close my server which is odd. Is there something else I should be doing. As the title says because the toasts are not working I have no indication if the code is actually doing anything. I just have a blank page.
I've added Internet to my manifest to allow the app access to that. If I visit the URL in my code (192.168.0.13/testdatabase.php) via my browser the data from my database shows up just fine.
Edit: The overall outcome I want from this eventually is to have some data from database displayed for my users to see. Instead of putting it in as static text and having to update the entire app just to update some data.
You need to implement your network connection on a separate thread for API level 11 or greater. Take a look on this link: HTTP Client API level 11 or greater in Android.
Also for the POST request, I think that you can use this code:
public String post(String str) {
String result = "";
try {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost postRequest = new HttpPost(SERVER_ADDRESS);
StringEntity input = new StringEntity(str);
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
result = getResult(response).toString();
httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
System.out.println(e.getMessage());
}
return result;
}
private StringBuilder getResult(HttpResponse response) throws IllegalStateException, IOException {
StringBuilder result = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())), 1024);
String output;
while ((output = br.readLine()) != null)
result.append(output);
return result;
}
This question already has answers here:
How to connect Android with MySQL using Mysql JDBC driver [duplicate]
(2 answers)
Closed 1 year ago.
I have been trying out the tutorials shown on various websites on connecting a MySQL database to android. At the moment the code below, takes the values which you hard code in, (i.e year=2005 and name=tom) and runs it through the php script. What I would like know is how I can modify this, so that it takes the values of what the user enters in a textbox instead.
package com.test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
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.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;
public class test 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 retrieval
txt.setText(getServerData(KEY_121));
}
public static final String KEY_121 = "http://***.****.com/mysqlcon.php"; //i use my real ip here
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","2005"));
nameValuePairs.add(new BasicNameValuePair("name","tom"));
//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")+
", name: "+json_data.getString("name")+
", sex: "+json_data.getInt("sex")+
", birthyear: "+json_data.getInt("birthyear")
);
//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;
}
}
Okay, I understand what do you want. You want to have an EditText or two in the app. The user will enter information in it and after pressing a button th information in the EditText should move into the mysql database. So, you want to make a dynamic app that inserts record into mysql. For that do the following to modify the above java code.
Insert following line below, TextView txt;
EditText editTxt;
Below rootLayout.addView(txt); insert following two lines,
editTxt = new EditText(this);
rootLayout.addView(editTxt);
Now, modify this line, nameValuePairs.add(new BasicNameValuePair("name","tom")); to fetch value from the EditText.
nameValuePairs.add(new BasicNameValuePair("name",editTxt.getText().toString()));
You can also create one for year.
This question already has answers here:
How to do a HTTP Post in Android?
(2 answers)
Closed 7 years ago.
I am working on an SMS Sending application and for login purpose i want to send the username and password using POST method from my Android Application to the web server.
When I click on lo-gin button the application is not responding and the console prints the following message in response of the Post request.
HTTP/1.1 500 Internal Server Error
While my application running fine with the GET method.
I am not able to figure out why this is causing...
the whole code is here:
package com.vikas.httplogin;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class HttpLogin extends Activity {
TextView tv;
private static final String tag ="FATAL_ERROR";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
connecttoServer();
}
private void connecttoServer()
{
BufferedReader br = null;
try
{
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost("url of my site");
List<NameValuePair> params = new ArrayList<NameValuePair>(3);
params.add(new BasicNameValuePair("username","vikaspatidar"));
params.add(new BasicNameValuePair("password", "patidar"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params);
request.setEntity(entity);
Log.v(tag,request.getMethod().toString());
HttpResponse response = client.execute(request);
Log.v(tag, response.getStatusLine().toString());
br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = br.readLine()) != null) {
sb.append(line + NL);
}
br.close();
String result = sb.toString();
Log.v(tag, result);
} catch (ClientProtocolException e)
{
Log.v(tag, e.getMessage());
}
catch (IllegalStateException e) {
Log.v(tag, e.getMessage());
} catch (IOException e) {
Log.v(tag, e.getMessage());
}
}
}
That's definitely looks like server-side error, not android problem. Look at server log files.
The way you're setting parameters to request looks weird, try setting parameters like this:
HttpPost post = new HttpPost("url of my site");
BasicHttpParams basicHttpParams = new BasicHttpParams();
basicHttpParams.setParameter("username", "vikaspatidar");
basicHttpParams.setParameter("password", "patidar");
post.setParams(basicHttpParams);
//...
Here is solution for this:
How to do a HTTP Post in Android?