首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何访问android的在线数据库?

如何访问android的在线数据库?
EN

Stack Overflow用户
提问于 2014-03-31 20:46:44
回答 2查看 93关注 0票数 0

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

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

下面是我的代码。

MainActivity.java

代码语言:javascript
复制
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

代码语言:javascript
复制
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;

    }
}

请指点。如有任何建议,将不胜感激。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-03-31 20:53:15

您的URL是内部的,因此不能从外部网络访问。您需要为它分配一个外部IP。http://192.168.1.145/

票数 1
EN

Stack Overflow用户

发布于 2014-03-31 20:53:43

我个人会使用sqllite数据库,但也许这个链接意志对你有帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22771843

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档