I managed to build a JSON array and I have a onClick event where I send this JSONArray through POST towards a php file that will process the array.
Right now I have no idea if the array arrives at the destination or not, if the array is interpreted correctly by the PHP or not.
The code for my POST call (Android) is:
Button bsave = (Button) findViewById(R.id.button3);
View.OnClickListener eventHandlerx = new View.OnClickListener() {
#Override
public void onClick(View arg0) {
JSONObject j1;
JSONArray jsonarray=new JSONArray();
ListView lst = (ListView) findViewById(R.id.mylistview);
int count = lst.getCount();
for (int i = 0; i < count; i++)
{
ViewGroup row = (ViewGroup) lst.getChildAt(i);
TextView tvId = (TextView) row.findViewById(R.id.fID);
TextView tvNume = (TextView) row.findViewById(R.id.fTitlu);
TextView tvUM = (TextView) row.findViewById(R.id.fUM);
TextView tvPU = (TextView) row.findViewById(R.id.fPU);
TextView tvCant = (TextView) row.findViewById(R.id.fCant);
jsonarray.put("Item");
j1 = new JSONObject();
try {
j1.put("idx", newid);
j1.put("id", tvId.getText());
j1.put("nume", tvNume.getText());
j1.put("um", tvUM.getText());
j1.put("pu", tvPU.getText());
j1.put("cant", tvCant.getText());
} catch (JSONException e) {
e.printStackTrace();
}
jsonarray.put(j1);
}
Log.d("JSON array","Array to send:"+jsonarray.toString());
sendJson( urlx, jsonarray);
}
private void sendJson(final String urlx, final JSONArray jsonarray) {
Thread t = new Thread() {
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
try {
HttpPost post = new HttpPost(urlx);
StringEntity se = new StringEntity( jsonarray.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/*Checking response */
if(response!=null){
HttpEntity entity = response.getEntity();
if (entity != null) {
Log.e("POST response",EntityUtils.toString(entity));
}else{
Log.e("POST response","NULL "+EntityUtils.toString(entity));
}
}else{
Log.e("POST response","NULL");
}
} catch(Exception e) {
e.printStackTrace();
Log.e("postJSON","Error at POST with json:"+e.toString());
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
};
bsave.setOnClickListener(eventHandlerx);
How do I check if the array was successfully POSTED to php? I assume I could do it in a php file... But how do I see the result?
No matter what I do, the Log shows me:
org.apache.http.conn.EofSensorInputStream#somehexa
So I am stuck. Please give me some solutions.
What should a php file look like in order to return the POSTED value, and what should my Android code look like in order to interpret the result (just display it somewhere like Log for debugging purposes)
The php I use is:
<?php
ob_start();
var_dump($_POST);
die();
$json = file_get_contents('php://input');
$obj = json_decode($json);
print $obj;
result = $obj;
$page = ob_get_contents();
ob_end_flush();
$fp = fopen("output.txt","w");
fwrite($fp,$page);
fclose($fp);
?>
However, the file does not show up...
and Eclipse does not give me anything in Log...
Thank you
If this is just for testing the easiest way to see the data is to do var_dump($_POST); inside PHP file you are submitting the form to, and log the response to some file on web server or to console in your android app. You can put die(); after var_dump if you want to break the execution of the rest of the code while you are testing.
edit:
Since you are using php://input stream and already have some code you can just use var_dump($json) or just echo it back you your app instead of what i suggested earlier. This will return the raw data you posted but you will need some kind of code in your app to display the HttpResponse. You can try something like this:
HttpEntity entity = response.getEntity();
String phpResponse = EntityUtils.toString(entity);
and then log the phpResponse variable.
Also, your file is not generated since everything after die(); is not executed, you can remove it and check again if the file is there.
Related
So, I know this might seems like a repeated question, but bear with me for a moment. In Android Studio, instead of using any external libraries (i.e., no JSON, no Volley, no Retrofit, nothing external), I plan to use simple runnable threads. These will fetch data using PHP stored on the localhost through the IP address of the WiFi which my system is using.
I know how to send a PHP update (the actual update codes are in PHP script), it's done like this:
Runnable runnableToUpdateDb = new Runnable() {
#Override
public void run() {
Log.d("DEBUG","RUNNING RUNNABLE");
try {
URL url = new URL("http://192.168.43.242/myapi/php_name.php");
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.connect();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String response = bufferedReader.readLine();
Log.d("DEBUG", response);
httpURLConnection.disconnect();
}catch (Exception e){
Log.d("DEBUG",e.toString());
}
}
};
And then simply running the PHP using thread upon the press of the button by:
Thread threadToUpdateDb = new Thread(runnableToUpdateDb);
threadToUpdateDb.start();
Now, the problem is in setting up a TextView that shows the updated/new data from the database though a different PHP.
The id I've described for this TextView in the layout is:
android:id="#+id/getdata"
I need help for implementing it in MainActivity.
The output for PHP is in the form of:
<br>8<br>
Here's how you perform a HTTP GET to an URL using plain Android. In this case I choose an AsyncTask so it would run the request aside from the Main Thread:
private class TareaGetFromDB extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String URL = params[0];
String response = null;
try {
// Create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpGet post = new HttpGet(URL);
// Perform the request and check the status code
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200) {
// code 200 equals HTTP OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
try {
response = IOUtils.toString(content, "utf-8");
} catch (Exception ex) {
// TODO handle exception
}
}
} catch(Exception ex) {
// TODO handle exception
}
return response;
}
#Override
protected void onPostExecute(String response) {
TextView myTextView = findViewById(R.id.getdata);
myTextView.setText(response);
}
}
This AsyncTask takes a String (the URL) as argument and returns a String (the response).
So you'll need to call it like this:
new TareaGetFromDB().execute("http://url.to/get/data");
You may need additional work before setting the text to the TextView to remove the surronding <br>, or you can remove them from the server response
Hey guys im creating an app where it populates a list view with data from mysql, the data that will fill the list view consists of courseid, courseName and lecturerName. However when i click the button to view the list it creates the progress dialog as it should however it gets stuck and then the application stop responding.
Below is the code to which i believe is causing the error because the logcat mentions something about doInBackground which is in this class:
the log cat file is: http://gyazo.com/950bcce9d14f267f495a4801434c6151
i really appreciate your time and help, i further want to say i am sorry about my debugging skills im still getting used to android.
public class AllCoursesActivity extends ListActivity {
//progress dialog
private ProgressDialog pDialog;
//create json parser object to understand the php files that were created
JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> courseList;
//url to get all the product list
private static String url_all_courses = "http://10.0.0.2/get_all_courses.php";
//JSON node Names
private static final String TAG_SUCCESS = "success";
private static final String TAG_COURSES = "courses";
private static final String TAG_COURSEID = "courseid";
private static final String TAG_COURSENAME = "courseName";
//products JSON array
JSONArray courses =null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.allcourses);
//hashmap for listview
courseList = new ArrayList<HashMap<String, String>>();
//loading courses in background thread
new LoadAllCourses().execute();
//GET list view
ListView lv = getListView();
}
class LoadAllCourses extends AsyncTask<String, String, String>{
//before starting the background thread show some progress dialog
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(AllCoursesActivity.this);
pDialog.setMessage("Loading Courses. Please Wait");
pDialog.setCancelable(false);
pDialog.setIndeterminate(false);
pDialog.show();
}
//getting all products from the URL
#Override
protected String doInBackground(String... args) {
//building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
//Getting JSON String from URL
JSONObject json = jsonParser.makeHttpRequest(url_all_courses, "GET", params);
//check log cat for json response
Log.d("All Products: ", json.toString());
try {
//checking for success TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1){
//it means courses were found
//Getting Array of products
courses = json.getJSONArray(TAG_COURSES);
//looping through all products
for (int i = 0; i < courses.length(); i++){
JSONObject c = courses.getJSONObject(i);
//storing each JSON Item in the variable
String courseid = c.getString(TAG_COURSEID);
String coursename = c.getString(TAG_COURSENAME);
//creating new HASHMAP
HashMap<String, String> map = new HashMap<String, String>();
//adding each child node to hashmap key => value
map.put(TAG_COURSEID, courseid);
map.put(TAG_COURSENAME, coursename);
//adding Hash list to array list
courseList.add(map);
}
}else {
//no courses found
//go back to dashboard
Intent i = new Intent(getApplicationContext(),MainScreenActivity.class);
//closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
}catch(JSONException e){
e.printStackTrace();
}
return null;
}
//after completing background task Dismiss the progress dialog
protected void onPostExecute(String file_url){
//dismiss the dialog after getting all the courses
pDialog.dismiss();
//updating ui from background thread
runOnUiThread(new Runnable() {
#Override
public void run() {
//updating parsed JSon data into list view
ListAdapter adapter = new SimpleAdapter(AllCoursesActivity.this, courseList,
R.layout.listcourse, new String[]{TAG_COURSEID, TAG_COURSENAME},
new int[]{R.id.courseid, R.id.coursename});
//updating listview
setListAdapter(adapter);
}
});
}
}
}
Edit: Sorry if i didnt include my JSONParser class
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
}
//function to get url
//by making post or get method
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {
//making the http request
try {
//check for request method
if (method == "POST") {
//request method is post
//default http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
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, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null){
sb.append(line + "\n");
}
is.close();
json = sb.toString();
}catch (Exception e){
Log.e("Buffer Error", "Error converting result" + e.toString());
}
//try parse the string to json object
try {
jObj = new JSONObject(json);
}catch (JSONException e) {
Log.e("JSON Parser", "Error Parsing data" + e.toString());
}
return jObj;
}
}
You're getting a NullPointerException and it's probably happening here:
Log.d("All Products: ", json.toString());
Search for "caused by" in your log cat output. It says that it was caused by attempting to use org.json.JSONObject.toString() on a null object. Add a check to make sure your object isn't null before you use it.
It looks like your JSON object is set to null on this line:
Log.d("All Products: ", json.toString());
Add a null check for your JsonObject before you log it.
It looks like we used the same tutorial for this, see my slightly different working implementation here:
https://github.com/dmnugent80/ShareApp/blob/master/app/src/main/java/com/share/daniel/share/MainActivity.java
Here is how to check if null:
if (json != null){
Log.d("MyApp", "All Products: " + json.toString());
}
else{
Log.d("MyApp", "json is null ");
}
Hey thank you for all the help but i realised what the problem was. You guys were right in that it could not return anything but this is because it wasnt connecting to the databaseproperly. i used my ip address from ip config and also i didnt link the php file correctly for example:
http://192.xxx.xx.x/android_api/get_all_courses.php
This above fixed the problem thanks for all the help and solutions
Hey all I am writing an android aplication which gets a JSON object from a node.js server. My code is below (I do not have access to the server code). Is there any way to consistently check the server for a change in the JSON object (if they update it)? Right now it only does one GET and stops. I want to be able to query for a change and continue working with the new updates. Thoughts? Thanks.
Called from OnCreate():
new Read().execute("JSONkey");
Here is my Read ASyncTask:
public class Read extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String...param) {
try {
read_json = getCoords();
httpText.append(read_json.toString() + "\n");
try{
}catch(Exception e){ e.printStackTrace(); }
JSONArray data = read_json.getJSONArray(param[0]);
for (int i = 0; i < data.length(); ++i){
JSONObject info = data.getJSONObject(i);
Coordinate pt = new Coordinate(info.getInt("point"), info.getString("name"), info.getDouble("lat"), info.getDouble("long"));
coords.put(pt.getPoint(), pt);
coordList.add(new GeoPoint(pt.getLat(),pt.getLong()));
}
return "Success"; //get "text"
} catch (Exception e){
return "Fail";
}
}
#Override
protected void onPostExecute(String result){
//Doing something with JSON
//new Read().execute("coords"); tried doing this, but I feel it is not right.
}
}
and the GetCoords():
public JSONObject getCoords()
throws ClientProtocolException, IOException, JSONException{
StringBuilder url = new StringBuilder(URL);
HttpGet get = new HttpGet(url.toString());
HttpResponse response = client.execute(get);
int status = response.getStatusLine().getStatusCode();
if(status == 200){
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONObject last = new JSONObject(data);
return last;
}else{
return null;
}
}
The proper way to do this is with a WebSocket but given the constrain of not being able to control the server side, your best bet is to
Put your code inside a service:
http://developer.android.com/reference/android/app/IntentService.html
Then use the Alarm Manager to schedule periodic updates.
http://developer.android.com/reference/android/app/AlarmManager.html
i am new to android and i am using mysql database where i am linking php file for connection which is working fine but my code is not displaying anything it is only showing background color black instead of displaying the data from the database
public class HomeFragment extends Fragment {
GridView gv;
#SuppressLint("NewApi")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.home, container, false);
StrictMode.enableDefaults();
gv = (GridView) rootView.findViewById(R.id.gridView_home);
getData();
return rootView;
}
public void getData(){
String result = "";
InputStream isr = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.2/Android/App/getcu.php"); //YOUR PHP SCRIPT ADDRESS
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
gv.setFilterText("Couldnt connect to database "+ e.getMessage()); //not printing anything
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
s = s +
"Name : "+json.getString("FirstName")+" "+json.getString("LastName")+"\n"+
"Age : "+json.getInt("Age")+"\n"+
"Mobile Using : "+json.getString("Mobile")+"\n\n";//+
"Artist:"+json.put("Images",true ); // not printing anything
}
gv.setFilterText(s); // not printing showing empty
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data "+e.toString()); }
} }
one more error while retrieving images from folder Android/pictures/image1 json is not printing the particular image deployed into database
"Artist:"+json.put("Images",true );
is the above statement correct to retrieve the images using json or i have to correct it
please help me to correct the above program thanks for your valuable time i am not able to understand why it is not printing anything but it is working when i extend it to activity how to use it in fragment
Ok, to avoid adding more comments:
Make sure you have the correct JSON data in your result string. Logging can help with tasks like that. Or maybe just use a Toast to just display the string to verify it's correct.
gv.setFilterText(s); will not cause any output. To display strings in the GUI you should use a TextView item that you put inside your layout, GridView in this case, and setText() on it.
I'm tearing my hair out over this problem I am having. I am trying to allow a user to upload some data from their android application to a website service which I have developed.
The data is to be uploaded using JSON and Android to a PHP web service which will then 'INSERT' the data into my PostgreSQL database.
I am unsure where the logic error is in my whole application as the app produces no errors at runtime but when I check the database records of my PostgreSQL server space there has been no data committed.
Please see below the code I am using and please try to help identify where I am going wrong. I have looked for tutorials on Google but they all are based on reading data FROM a PHP web service to an android app but I am looking to send the original data from the android app.
DataPost Activity
public void postData() throws JSONException{
Toast.makeText(DataSummary.this, "Done! Check your profile online to see your record.", Toast.LENGTH_LONG).show();
Thread trd = new Thread(new Runnable(){
public void run(){
//Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://users.aber.ac.uk/dwd/mfb/php/jsonscript.php");
JSONObject json = new JSONObject();
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(), i);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] ba = bao.toByteArray();
String ba1=Base64.encodeToString(ba, i);
try {
//JSON data:
json.put("photo", ba1.toString());
json.put("name", name);
json.put("description", description);
json.put("latitude", latitude);
json.put("longitude", longitude);
json.put("project", project);
json.put("owner", username);
JSONArray postjson = new JSONArray();
postjson.put(json);
//Post the data
httppost.setHeader("json", json.toString());
httppost.getParams().setParameter("jsonpost", postjson);
//Execute HTTP Post Request
System.out.println(json);
HttpResponse response = httpclient.execute(httppost);
//for JSON
if(response != null)
{
InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try{
while((line = reader.readLine()) != null){
sb.append(line + "\n");
}
} catch (IOException e){
e.printStackTrace();
} finally {
try {
is.close();
} catch(IOException e){
e.printStackTrace();
}
}
}
} catch(ClientProtocolException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
trd.start();
}
PHP Webservice
<?php
session_start();
$conn = pg_connect("database_string");
//VARIABLES TO BE WRITTEN TO THE DATABASE
$photo = $_REQUEST["photo"];
echo $photo;
$binary=base64_decode($photo);
header('Content-Type: bitmap; charset=utf-8');
$name = json_decode(stripslashes($_POST["name"]));
$safe_name = pg_escape_string($name);
$desc = json_decode(stripslashes($_POST["description"]));
$safe_desc = pg_escape_string($desc);
$latitude = json_decode(stripslashes($_POST["latitude"]));
$longitude = json_decode(stripslashes($_POST["longitude"]));
$project = json_decode(stripslashes($_POST["project"]));
$owner = json_decode(stripslashes($_POST["owner"]));
$id = pg_query("SELECT * FROM users WHERE email = $owner");
$id_assoc = pg_fetch_assoc($id);
$id_res = $id_assoc['u_id'];
//SQL STATEMENT HERE FOR INSERT
$res = pg_query("INSERT INTO records (photo, name, description, latitude, longitude, project, owner) VALUES ('$photo', '$safe_name', '$safe_desc', '$latitude', '$longitude', '$project', '$id_res'");
pg_close($conn);
?>
Anyone who can provide some advice/tutorials/code solutions would be a hero in my book!
Does the SELECT query return anything? I'm not a PHP expert but to me it looks like you're sending the variables wrong so there shouldn't be:
$id = pg_query("SELECT * FROM users WHERE email = $owner");
But
$id = pg_query("SELECT * FROM users WHERE email ='".$owner."'");
Similar for the INSERT query.
Other thoughts:
don't do a SELECT * when you just want one column it will be slower. For example with index-only-scans in 9.2 you could return the id straight from the index(email,id)
if you want to use just the id of the user it's better to put it in the subquery of the insert query
INSERT INTO records ( ... ,owner) VALUES (... ,(SELECT id FROM users WHERE email='".$owner."')")
You could even add RETURNING owner at the end to get the owner id out from the insert query if you need it somewhere else.