如何在android中访问在线数据库?

时间:2014-03-31 20:46:45

标签: android

我正在创建一个应用程序,用户提交注册表单并将表单数据更新到远程服务器上维护的数据库中。

我使用本地主机作为服务器。我的应用程序在模拟器上测试时工作正常。 但是,当我在手机上运行具有不同互联网连接的应用程序时,应用程序正常运行,没有错误,但我的localhost上的数据库没有更新。

请按照下面的代码。

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;

    }
}

请指导。 任何建议将不胜感激。

2 个答案:

答案 0 :(得分:1)

您的网址是内部网址,因此无法从外部网络访问。您需要为其分配外部IP。 http://192.168.1.145/

答案 1 :(得分:0)

我个人会使用sqlite数据库,但也许link will对你有所帮助