我正在製作一個應用程序,由用戶提交註冊表單並將表單數據更新到遠程服務器上維護的數據庫中。如何在android中訪問在線數據庫?
我正在使用本地主機作爲服務器。我的應用程序在模擬器上測試時工作正常。 但是,當我運行我的手機上有不同的互聯網連接的應用程序,應用程序工作正常,沒有錯誤,但我的本地主機上的數據庫不更新。
請按照下面的代碼。
MainActivity.java
package com.mits_form;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity 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 urlcreateproduct = "http://192.168.1.145/androidconnect/createproduct.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pDialog = new ProgressDialog(this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
// Edit Text
inputName = (EditText) findViewById(R.id.editText1);
inputPrice = (EditText) findViewById(R.id.editText2);
inputDesc = (EditText) findViewById(R.id.editText3);
// Create button
try
{
Button btnCreateProduct = (Button) findViewById(R.id.button);
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view) {
// creating new product in background thread
new CreateNewProduct().execute();
}
});
}
catch(Exception ex)
{
Log.e("MITS FORM", ex.toString());
}
}
// 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()
{
/*
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);*/
pDialog.show();
}
/**
* Creating product
* */
protected String doInBackground(String... args) {
try{
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(urlcreateproduct,"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) {
Toast.makeText(getApplicationContext(), " form submitted", Toast.LENGTH_LONG).show();
// successfully created product
// Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
//startActivity(i);
// closing this screen
// finish();
} else {
// failed to create product
}
} catch (JSONException e)
{
System.out.println("in catch of json exception");
Toast.makeText(getApplicationContext()," in catch",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
} catch (Exception ex) {
Log.e("MITS", ex.toString());
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
Toast.makeText(getApplicationContext(),"finished...",Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
}
}
JSONParser.java
package com.mits_form;
/**
* Created by vanja on 3/29/14.
*/
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;
}
}
請指導。 任何建議將不勝感激。
我沒有看到有關此更新數據庫什麼。另外,你確定沒有錯誤嗎?張貼日誌。 – njzk2