Android将数据插入实时mysql数据库

Posted

技术标签:

【中文标题】Android将数据插入实时mysql数据库【英文标题】:Android insert data into a live mysql database 【发布时间】:2017-07-27 13:40:18 【问题描述】:

我正在尝试将编辑文本中的数据插入实时数据库,但是当我按下应该发送数据的按钮时应用程序崩溃。

  public class MainActivity extends Activity 
    Button add_btn,view_btn;
    TextView txt;

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    add_btn=(Button)findViewById(R.id.add_btn);
    view_btn=(Button)findViewById(R.id.view_btn);
    txt=(TextView)findViewById(R.id.textView1);
    ConnectivityManager connectivityManager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
    if(networkInfo!=null && networkInfo.isConnected())
        txt.setVisibility(View.INVISIBLE);
    
    else
       
        add_btn.setEnabled(false);
        view_btn.setEnabled(false);
        txt.setVisibility(View.VISIBLE);
    

public void add_user(View view)

    startActivity(new Intent(this,Add_user.class));


public void view_user(View view)




        


       public class Add_user extends Activity 
    EditText name,username,pass;
    Button add_user;
   String name1,username1,pass1,method;

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_user);
    name=(EditText)findViewById(R.id.username);
    username=(EditText)findViewById(R.id.name);
    pass=(EditText)findViewById(R.id.pass);
    add_user=(Button)findViewById(R.id.button1);

public void add(View view)
    name1=name.getText().toString();
    username1=username.getText().toString();
    pass1=pass.getText().toString();
    BackgroundTask backgroundTask=new BackgroundTask();
    backgroundTask.execute(name1,username1,pass1);
    finish();

class BackgroundTask extends AsyncTask<String, Void, String> 
    String url;
    @Override
    protected void onPreExecute() 
        url="http://douxtoile.com/add_user.php";
        Toast.makeText(getApplicationContext(), url,Toast.LENGTH_LONG).show();

    
    @Override
    protected String doInBackground(String... params) 
        String name=params[1];
        String username=params[2];
        String pass=params[3];
        Toast.makeText(getApplicationContext(), name+""+username+""+pass,Toast.LENGTH_LONG).show();
        try 

                URL url1=new URL(url);
                HttpsURLConnection httpsURLConnection=(HttpsURLConnection)url1.openConnection();
                httpsURLConnection.setRequestMethod("POST");
                httpsURLConnection.setDoOutput(true);
                OutputStream os=httpsURLConnection.getOutputStream();
                BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
                String data=URLEncoder.encode("user","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+"&"+
                        URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8")+"&"+
                        URLEncoder.encode("pass","UTF-8")+"="+URLEncoder.encode(pass,"UTF-8");
            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            os.close();
            InputStream is=httpsURLConnection.getInputStream();
            is.close();
            httpsURLConnection.disconnect();

             catch (MalformedURLException e) 
                // TODO Auto-generated catch block
                e.printStackTrace();
            
        catch(NullPointerException e)
            Toast.makeText(getApplicationContext(), e.toString(), 0).show();

        
        catch (IOException e) 
                // TODO Auto-generated catch block
                e.printStackTrace();

        
        return "Success";
    
    @Override
    protected void onProgressUpdate(Void... values) 
        // TODO Auto-generated method stub
        super.onProgressUpdate(values);
    
    @Override
    protected void onPostExecute(String result) 
        // TODO Auto-generated method stub
        Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
    



 

这是我的错误日志。

Stacktrace: 
          03-07 16:05:34.324: E/androidRuntime(24090): FATAL EXCEPTION:        AsyncTask #2
          03-07 16:05:34.324: E/AndroidRuntime(24090): Process:     com.example.demo_online_db, PID: 24090
          03-07 16:05:34.324: E/AndroidRuntime(24090):   java.lang.RuntimeException: An error occured while executing doInBackground()
          03-07 16:05:34.324: E/AndroidRuntime(24090):  at android.os.AsyncTask$3.done(AsyncTask.java:300) 
          03-07 16:05:34.324: E/AndroidRuntime(24090):  at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
          03-07 16:05:34.324: E/AndroidRuntime(24090):  at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
          03-07 16:05:34.324: E/AndroidRuntime(24090):  at java.util.concurrent.FutureTask.run(FutureTask.java:242)
          03-07 16:05:34.324: E/AndroidRuntime(24090):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
          03-07 16:05:34.324: E/AndroidRuntime(24090):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
          03-07 16:05:34.324: E/AndroidRuntime(24090):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
          03-07 16:05:34.324: E/AndroidRuntime(24090):  at java.lang.Thread.run(Thread.java:818)
          03-07 16:05:34.324: E/AndroidRuntime(24090): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=3; index=3
          03-07 16:05:34.324: E/AndroidRuntime(24090):  at com.example.demo_online_db.Add_user$BackgroundTask.doInBackground(Add_user.java:54)
          03-07 16:05:34.324: E/AndroidRuntime(24090):  at com.example.demo_online_db.Add_user$BackgroundTask.doInBackground(Add_user.java:1)
          03-07 16:05:34.324: E/AndroidRuntime(24090):  at android.os.AsyncTask$2.call(AsyncTask.java:288)
          03-07 16:05:34.324: E/AndroidRuntime(24090):  at java.util.concurrent.FutureTask.run(FutureTask.java:237)
          03-07 16:05:34.324: E/AndroidRuntime(24090):  ... 4 more
          03-07 16:05:35.985: E/OpenGLRenderer(24090): SFEffectCache:clear(), mSize = 0

我没有包含任何外部罐子,实际上我是新手,所以不知道我这样做是对还是错。 php脚本很好,我已经静态测试过。

【问题讨论】:

启动后台任务后为什么要调用finish() String name=params[0]; String username=params[1]; String pass=params[2]; @PavneetSingh 哦,我错过了。 返回上一个活动。 应用程序崩溃并显示一个对话框,说不幸的是 app_name 已停止 【参考方案1】:

以这种方式获取您的字符串值...

        String name=params[0];
        String username=params[1];
        String pass=params[2];

【讨论】:

您可以将 Toast 包装在 runOnUIThread() 中,但这不是最佳解决方案。当发生错误时,您应该在 catch 块中设置一个布尔标志,然后在标志为 true 时在 onProgressUpdate()、onPostExecute() 或任何其他具有 UI 访问权限的方法中显示适当的 Toast【参考方案2】:

在此处进行 3 处更改

1)

public void add(View view)
    name1=name.getText().toString();
    username1=username.getText().toString();
    pass1=pass.getText().toString();
    BackgroundTask backgroundTask=new BackgroundTask();
    backgroundTask.execute(name1,username1,pass1);
    //finish();

2)

@Override
protected String doInBackground(String... params) 
    String name=params[0];
    String username=params[1];
    String pass=params[2];

3)

@Override
    protected void onPostExecute(String result) 

        Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
        finish();
    

【讨论】:

应用仍然崩溃。即使我注释了 doInBackground 中的所有代码并打印了一个不起作用的 toast,应用程序也会崩溃。 注释掉backgroundTask.execute(name1,username1,pass1);后在此处附加新的日志猫 03-07 16:46:47.156: D/ViewRootImpl(15597): ViewPostImeInputStage ACTION_DOWN

以上是关于Android将数据插入实时mysql数据库的主要内容,如果未能解决你的问题,请参考以下文章

mysql批量插入数据

Google Dataflow (Apache beam) JdbcIO 批量插入 mysql 数据库

数据未插入 Firebase 实时数据库抛出 Android

PHP从Android将JSON数据插入MySQL数据库

无法使用 Kotlin Retrofit 将数据从 Android 插入到 Mysql [重复]

如何将 Dbase 数据库实时复制到 MYSQL?