Android app sending a string to display on a webpage

I've been trying to create an Android app and webpage for months now, where the app sends a simple string to the website and the website displays that text. I've tried many tutorials, but they are all incomplete or old.

SOLUTION

As I am just a n00b as it comes to coding I wasn't able to tell whether the suggestions were the whole story or just a part of the story. It turned out that I only got a part of the story.

My objective was: to create an Android app and webpage, where the app sends a simple string to the website and the website displays that text for everyone to see. That last part I didn't mention in my question. So asking complete helps to get the right answer.

There were a couple of steps I had to take:

  1. Register a domainname (that I did)
  2. Contract a hosting service (that I did)
  3. Upload a php-file with HasH's code (see below) to the file manager for your webpage in the topdirectory of that webpage, make sure that no content manager is running for that domain or subdomain (here I made a mistake: I had Parallels Presence Builder running on the target domain. Because it always uses a template I wasn't able to publish a 'clean' version of the php-file. That resulted in my webpage giving back junk information starting with <!DOCTYPE etc. I created a new subdomain without content management and uploaded a php-file with Hash's php-code. It worked perfectly)
  4. Then I created the Android app using Hash's code (see below, don't forget the .jar-files AND don't forget to add the .jar-files as library!).
  5. As my question was incomplete Hash's code doesn't deal with the part that the webpage has to display the text for everyone to see. As php is personal for every user I had to make an addition to the code.

See here:

<?php
$msg = $_POST['msg'];
if($_SERVER['REQUEST_METHOD']=='POST'){
$myfile = fopen("yourfilename.txt", "a") or die("Unable to open file!");
fwrite($myfile, $msg . "\n");
fclose($myfile);    
}

$myfile = fopen("yourfilename.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("yourfilename.txt"));
fclose($myfile);
?> 

Upvotes: 1

Views: 377

Answers (1)

M.Fakhri
M.Fakhri

Reputation: 184

Alright, let me give you a very simple way to connect your application with PHP Service page... First you have to make sure you already has this libraries: 1- http-core-4.1.jar 2- httpclient-4.0.3.jar

Then create a new class name it "JSONParser" and paste this code:

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
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.io.UnsupportedEncodingException;
import java.util.List;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
                                      List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                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"){
                // request method is 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 a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

Well, now go to your main activity and do it as this:

public class MainActivity extends AppCompatActivity {
JSONParser jparser = new JSONParser(); 
 ProgressDialog pdialog;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

String msg = "Hello";

new connector().execute(msg); //This will create a new thread to connect with your service page.


}

//The AsyncClass connector..



 class connector extends AsyncTask<String,String,String> {
        @Override
        protected void onPreExecute(){
            pdialog = new ProgressDialog(MainActivity.this);
            pdialog.setMessage("Sending Hi...");
            pdialog.setCancelable(false);
            pdialog.setIndeterminate(false);
            pdialog.show();
        }
        //ArrayList to carry your values
        List<NameValuePair> data = new ArrayList<>();

        @Override
        protected String doInBackground(String... params) {

            try {

                    data.add(new BasicNameValuePair("msg",params[0])); //here we sit the key "msg" to carry your value which you passed on thread execute.

  //Then create the JSONObject to make the rquest and pass the data(ArrayList).              
 JSONObject json = jparser.makeHttpRequest("Http://example.com/mypage.php","POST",data);

/*In case you want to receive a value from your page you should do something like this..
String getString = json.getString("key1");
Int getInt = json.getInt("key2");
key1,key2 are keys that you send from your page.
*/





            } catch (Exception e) {
               /* Any Exception here */
            }

            return null;

        }

        @Override
        protected void onPostExecute(String file_url){
            pdialog.dismiss();
              // This After the thread did it's operate
/* For Example you Toast your key1,key2 values :D*/

            }
    }



}

In your PHP page you should do as the following..

<?php
//In case of receive..
$msg = $_POST['msg']; 
echo $msg;

//In case of send..
$values = array();
$values["key1"] = "Hello this is key1";
$values["key2"] = "Hello this is key2";
echo json_encode($values); //this will make a json encode which you can get it back in your application ;)

?>

Hope it helps :), and sorry for my bad English :v

Upvotes: 1

Related Questions