PDA

View Full Version : وب سرویس



mohammadreza761
پنج شنبه 03 بهمن 1392, 22:07 عصر
سلام دوستان .
میخواستم در مورد چند خط کد که مربوط به وب سرویس میشه برام توضیح بدین که چه کاری رو انجام میدن.
و اگه میتونید کد insert کردن (هم php و هم android )رو بهم بگید .

try{

BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");

}catch(Exception e){
Log.e("Fail 2", e.toString());
}

.................................................. .................... و

try{
JSONObject json_data=new JSONObject(result);
code=(json_data.getInt("code"));
if(code==1){
Toast.makeText(getBaseContext(), "inserted successfully", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getBaseContext(), "sorry . try again", Toast.LENGTH_SHORT).show();
}

}catch(Exception e){
Log.e("fail 3", e.toString());
}

rubiks.kde
جمعه 04 بهمن 1392, 12:59 عصر
تکه کد اول داره از is که یک InputStream است اطلاعات رو خط به خط تا انتها با کدینگ iso-8859-1 میخونه و تبدیل به یک string میکنه.
تکه کد دوم داره خروجی خوانده شده از تکه کد اول رو به یک شی json تبدیل میکنه.بعد هم چک میکنه که مقدار متغییر code در شی json چی هست.
اگه یک باشه یعنی عمل insert در سرور موفقیت آمیز بوده و الا هم نه.

اینم یه نمونه کد php

<?php

$host = '127.0.0.1';
$uname = 'root';
$pwd = '';
$db = 'webservice';

$con = mysql_connect($host, $uname, $pwd) or die('Connection Failed');
mysql_select_db($db, $con) or die('Database Selection Failed');
$sql = "insert into contact (name,phone) values ('".$_GET["name"]."','".$_GET["phone"]."')";
$query = mysql_query($sql, $con);
$main_arr = array();
if($query)
{
$main_arr[0]["state"] = true;
print(json_encode($main_arr));
}
else
{
$main_arr[0]["state"] = false;
print(json_encode($main_arr));
}
mysql_close($con);
?>

mohsen22
جمعه 04 بهمن 1392, 13:22 عصر
این هم نمونه کد اندروید

public class NewProductActivity extends Activity {

// Progress Dialog
private ProgressDialog pDialog;

JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputPrice;
EditText inputDesc;

// url to create new product
private static String url_create_product = "http://localhost/android_connect/create_product.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_product);

// Edit Text
inputName = (EditText) findViewById(R.id.inputName);
inputPrice = (EditText) findViewById(R.id.inputPrice);
inputDesc = (EditText) findViewById(R.id.inputDesc);

// Create button
Button btnCreateProduct = (Button) findViewById(R.id.btnCreateProduct);

// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
}

/**
* Background Async Task to Create new product
* */
class CreateNewProduct extends AsyncTask<String, String, String> {

/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}

/**
* Creating product
* */
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String price = inputPrice.getText().toString();
String description = inputDesc.getText().toString();

// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("price", price));
params.add(new BasicNameValuePair("description", description));

// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);

// check log cat fro response
Log.d("Create Response", json.toString());

// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);

if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);

// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}

return null;
}

/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}

}

mohammadreza761
جمعه 04 بهمن 1392, 15:41 عصر
دوستان این error رو توی logcat میده .
مشکلش چیه؟

01-24 12:55:20.939: E/fail 3(14905): java.lang.NullPointerException

rubiks.kde
جمعه 04 بهمن 1392, 18:29 عصر
ببینید کدوم قسمت این خطا رو میده و دوبار روش کلیک کنید تا به محل خطا برید.
احتمالا خروجی برای تبدیل به string هست.

abbasalim
جمعه 04 بهمن 1392, 19:10 عصر
http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/