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 tutoria
Solution 1:
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;
publicclassJSONParser {
staticInputStreamis=null;
staticJSONObjectjObj=null;
staticStringjson="";
// constructorpublicJSONParser() {
}
// function get json from url// by making HTTP POST or GET mehtodpublic JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP requesttry {
// check for request methodif(method == "POST"){
// request method is POST// defaultHttpClientDefaultHttpClienthttpClient=newDefaultHttpClient();
HttpPosthttpPost=newHttpPost(url);
httpPost.setEntity(newUrlEncodedFormEntity(params));
HttpResponsehttpResponse= httpClient.execute(httpPost);
HttpEntityhttpEntity= httpResponse.getEntity();
is = httpEntity.getContent();
}elseif(method == "GET"){
// request method is GETDefaultHttpClienthttpClient=newDefaultHttpClient();
StringparamString= URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGethttpGet=newHttpGet(url);
HttpResponsehttpResponse= httpClient.execute(httpGet);
HttpEntityhttpEntity= httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReaderreader=newBufferedReader(newInputStreamReader(
is, "iso-8859-1"), 8);
StringBuildersb=newStringBuilder();
Stringline=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 objecttry {
jObj = newJSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Stringreturn jObj;
}
}
Well, now go to your main activity and do it as this:
publicclassMainActivityextendsAppCompatActivity {
JSONParser jparser = newJSONParser();
ProgressDialog pdialog;
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String msg = "Hello";
newconnector().execute(msg); //This will create a new thread to connect with your service page.
}
//The AsyncClass connector..classconnectorextendsAsyncTask<String,String,String> {
@OverrideprotectedvoidonPreExecute(){
pdialog = newProgressDialog(MainActivity.this);
pdialog.setMessage("Sending Hi...");
pdialog.setCancelable(false);
pdialog.setIndeterminate(false);
pdialog.show();
}
//ArrayList to carry your valuesList<NameValuePair> data = newArrayList<>();
@OverrideprotectedStringdoInBackground(String... params) {
try {
data.add(newBasicNameValuePair("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 */
}
returnnull;
}
@OverrideprotectedvoidonPostExecute(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
Post a Comment for "Android App Sending A String To Display On A Webpage"