pass 2 variables in php android - php

Good day,
I have a php code that has a $_POST['Query'] function, i want to add it with $_POST['Tags'] but how can I pass 2 variables in android using to php, I had pass the a value to a $_POST['Query'] with my code but how can I pass the second one ?
OutputStream os = con.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
String data = URLEncoder.encode("Query", "UTF-8")+"="+URLEncoder.encode(query,"UTF-8");
bw.write(data);
bw.flush();
con.connect();
bw.close();
os.close();

Simply append another parameter with &
String data = URLEncoder.encode("Query", "UTF-8")+"="+URLEncoder.encode(query,"UTF-8");
data+= "&"+URLEncoder.encode("Tags", "UTF-8")+"="+URLEncoder.encode(yourTags,"UTF-8");
Note : For efficiency use StringBuilder
StringBuilder params = new StringBuilder();
params.append(URLEncoder.encode("Query", "UTF-8")+"="+URLEncoder.encode(query,"UTF-8"));
params.append("&");
params.append(URLEncoder.encode("Tags", "UTF-8")+"="+URLEncoder.encode(yourTagStr,"UTF-8"));
bw.write(params.toString());
// ... code

Related

How to add multiple data tags to BufferedWriter?

my Android application uploads string data to a PHP webservice. This usually works if I restrict myself to one single datum. However, I'm in a situation where I need to identify different datasets in my PHP script.
This is what I try:
URL url = new URL("....script.php") // This is my webservice
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequest("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStream outputStream = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter( new OutputSteramWriter(outputStream, "UTF-8"));
writer.write("datum1=" datum1json.toString());
writer.newLine();
writer.write("datum2=" datum2json.toString());
writer.close();
outputStream.close();
...
My PHP script begins like that
if(isset($_POST['datum1']) && isset($_POST['datum2'])) {
$json1 = json_encode($_POST['datum1']);
$json2 = json_encode($_POST['datum2']);
echo $json1;
echo $json2; }
As long as I append one single datum to my writer (writer.write("datum1=....) and only test for one incoming variable in the php, everything works fine. In my case, I get an EOFException
java.io.EOFException
at libcore.io.Streams.readAsciiLine(Streams.java:203)
at libcore.net.http.HttpEngine.readResponseHeaders(HttpEngine.java:560)
...
I do not suspect the PHP file, since it works with one set.
How do I attach two different datasets with identifiers to a writer?
I tried writer.write("datum1=" datum1json.toString() + "datum2=" datum2json.toString()); too, but no success.
I know about different methods of POST requests (HttpDefaultClient,..) but I'm not too familiar with them and my requirements and data sizes are actually quite low.
Thank you!
Try this,
String datum1 = URLEncoder.encode(datum1json.toString(), "UTF-8");
String datum2 = URLEncoder.encode(datum2json.toString(), "UTF-8");
String params = "datum1=" + datum1 + "&" + "datum2=" + datum2;
BufferedWriter writer = new BufferedWriter( new OutputSteramWriter(outputStream, "UTF-8"));
writer.write(params);
writer.close();
outputStream.close();

set language android to php-mysqli

I have an android application, that makes a connection to a PHP-script, which then fetches data from a database and returns the result. It all works fine and dandy, except for language-settings. I have set the language to dainsh and UTF-8, all the places I can think of, and when I send it to the database it is in danish, but the returnvalue is not in danish.
Here is my call to the PHP-script from android
URL url = new URL(selectUrl);
HttpURLConnection httpUrlConncetion = (HttpURLConnection) url.openConnection();
httpUrlConncetion.setRequestMethod("POST");
httpUrlConncetion.setDoInput(true);
httpUrlConncetion.setConnectTimeout(10000);
httpUrlConncetion.setRequestProperty("Accept-Language", "da_DK");
httpUrlConncetion.setRequestProperty("Content-type", "application/json");
httpUrlConncetion.connect();
String line = "";
StringBuilder sb = new StringBuilder();
int Httpresult = httpUrlConncetion.getResponseCode();
Log.d(TAG, httpUrlConncetion.getResponseMessage().toString());
if (Httpresult == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpUrlConncetion.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
while ((line = reader.readLine()) != null) {
sb.append(line);
list.add(line);
}
result=sb.toString();
for(int i=0;i<list.size();i++){
Log.d(TAG, "min nye list" + list.get(i) + "\n");
}
and the Logcat says
it is ,"minegen":"n\u00f8gler"} that is the problem. it should have been the danish "nøgler".
The php has been set like this in the connection-file to the database:
"mysqli_set_charset($con, "utf8");
and the mysqli-database has been set to danish language - like this
And I do get danish characters in the table when checking in the table
So what am I missing??
Any help would be highly appreciated :)
I once run into a issue like this it was about saving emojis like you i had all charset set correctly but no matter what i did it didn't work so finaly i end up using urlencode($content) when saving into my database and urldecode($content) when retrieving data
I had a problem like this for Persian characters and I solved it by bad way which worked for me. I just defined my own encoding and made two functions FAtoEN(s) and ENtoFA(s). FAtoEN changes each Persian char to an English char using keyboard keys. for example changes "ن" to "k" because I use k key on keyboard when the keyboard is persian and I want to write ن. and also the other function do this inverse.

sending array from android to php

I have an array
ArrayList<String> selectedItems = new ArrayList<String>();
and few strings
private String sq,tr;
am sending these values to a remote server via POST request
nameValuePair = new ArrayList<NameValuePair>(3);
nameValuePair.add(new BasicNameValuePair("sq", sq));
nameValuePair.add(new BasicNameValuePair("tr", tr));
nameValuePair.add(new BasicNameValuePair("sub[]", selectedItems);
My problem is am able to send strings but when I try to send the array am getting errors
Please suggest me the best way to send array as well as strings via post method or guide me if am making some mistake.
try to put that in loop
for (int i = 0; i < selectedItems.length; i++) {
nameValuePairs.add(new BasicNameValuePair("sub[]",selectedItems[i]));
}

how to compare JSON object with a string in android?

Below is the code. The code works perfectly fine. It displays the content when both the EditText is left blank or has some string value that is available in the mysql database . My problem is that i want to display an error message when the input from the editText does not match with the JSON object or the returnString that store the result of the Mysql query after decoding JSON.
for eg if input='abi' //input from edittext
khasi:abirt //khasi is column from the database with value abirt
output : khasi abirt will be displayed
but i want an error to be displayed when input does not match at all with any of the words from the khasi column of the database instead of a blank page activity.
for eg : input='kljfldskfsldhf'
khasi column does not consist the input word
outout : blank page activity
String result;
String returnString;// to store the result of MySQL query after decoding JSON
String input;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is most commonly used to catch accidental disk or network access on the application's main thread
.penaltyLog().build());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_meaning);
Intent intent = getIntent();
intent.setClass(DisplayMeaningActivity.this, MainActivity.class);
input =intent.getStringExtra(MainActivity.MEANING_INPUT);
tv = (TextView) findViewById(R.id.textView1);
// declare parameters that are passed to PHP script i.e. the name "meaning" and its value submitted by user
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
// define the parameter
String response = null;
// call executeHttpPost method passing necessary parameters
try {
response = CustomHttpClient.executeHttpPost(
"http://kffg.netii.net/konnect.php?name="+input, // your ip address if using localhost server
postParameters);
// store the result returned by PHP script that runs MySQL query
String result = response.toString();
//parse json data
try{
returnString = "";
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")+
", Khasi: "+json_data.getString("Khasi")+
", English: "+json_data.getString("English")
);
//Get an output to the screen
returnString += "\n\n" + "Kyntien : " + json_data.getString("Khasi") + "\n"+ "Meaning: " + "\n"+ "" + json_data.getString("English");
}
}
catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
need to use an if loop with stringValue.contains("editTextvalue") condition.
It'l be like:
if (inputString.contains(columnNames)) {
//yes
} else {
//no, then print error
}
Since you already have your "result" in String, that shouldn't be a problem (?) .
Did not exactly understand the columns of the database issue but for the khasi column of your database, you can make an arrayList of of names and compare the string with a for each loop.
for(String string: columnNames){
if(input.equals(name)){}
}
Maintain an arrayList where you add string for each time you get data for khasi like:
arrayList.add(json_data.getString("Khasi"));

JSONObject arrayList parsing in php

I am new to JSON. KIndly help me with the JSON parsing in php sent from android.
I have a class A, having members phoneNumber and name. I have an arrayList of object A
private ArrayList<A> contactList = new ArrayList<A>();
contactList.add(a1);
contactList.add(a2); [objects of A]
Now I am trying to send this arrayList to php server using JSON.
JSONObject json = new JSONObject();
json.put("contactList", contactList);
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("");
StringEntity se = new StringEntity("JSON: " + json.toString());
post.setEntity(se);
HttpResponse resP = client.execute(post);
Please let me know how to I parse it in the php server side to get phoneNumber and name of each object A.
I tried to create a same class A in the php server side and trying this way.
<?php
$contactList = array();
if(isset($_POST["contactList"])) {
$contactList = json_decode($_POST["contactList"]);
include_once './eachContactClass.php';
foreach ($contactList->contactList as $eachContact) {
$eachObj = new eachContactClass();
$eachObj = $eachContact;
$name = $eachObj->getName();
$phoneNumber = $eachObj->getPhone();
}
}
Please let me know whether the approach is correct, or kindly help me to correct it
First of all, may I suggest you to use a library for handling the JSON serialization/deserialization. GSON would be suited for your work.
Then, you should check the result JSON for validity before sending it to any remote server.
To parse it in PHP, use the json_decode() function that will return your an object representing your JSON. You can also get a hash if you prefer, just look in the doc.
I think your problem is that your JSON is invalid, as the JSONObject doesn't correctly serialize your ArrayList. Your should probably check that.

Categories