简体   繁体   English

Android使用AsyncTask连接MySql并以JSON或String形式返回数据

[英]Android connecting with MySql using AsyncTask and return data in form of JSON or String

I have been working to connect MySql database to my android app and searched on internet. 我一直在努力将MySql数据库连接到我的Android应用程序并在互联网上搜索。 Some of the solutions worked with one problem. 一些解决方案解决了一个问题。 The problem is that the function returns data in the form which is String and the content of String is : 问题是函数以String的形式返回数据,String的内容是:

[{"id":1,"username":"admin","password":"root","email":"admin@localhost.com","fullname":"Site Admin"}]

But I want the data in form of some sort of array through which I can get all the user data like email , fullname separately. 但是我希望数据以某种形式存在,通过它我可以分别获得所有用户数据,如电子邮件,全名。 I tried to implement a function but that didn't work. 我试图实现一个功能但是没有用。 Following is the code: 以下是代码:

BackgroundWorker.java

public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
String tresult;


BackgroundWorker (Context ctx){
    context = ctx;
}
@Override
protected String doInBackground(String... params) {
    String type = params[0];
    String username = params[1];
    String password = params[2];

    String login_url = "http://192.168.1.18/myproj/api/query1.php";
    if (type.equals("login")){
        try {
            URL url = new URL(login_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
            String post_data = URLEncoder.encode("username","UTF-8")+"="+URLEncoder.encode(username,"UTF-8")+"&"+
                    URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();

            outputStream.close();

            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
            String line="";
            String result="";

            while((line = bufferedReader.readLine())!= null){
                result+=line;
            }

            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();

            return result;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
    alertDialog = new AlertDialog.Builder(context).create();
    alertDialog.setTitle("Login Status");
}

@Override
protected void onPostExecute(String result) {
    alertDialog.setMessage(result);
    alertDialog.show();
    tresult = result;
    //return tresult;
}

@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}


}

BackgroundWorker is a class which works in background and connect with database. BackgroundWorker是一个在后台工作并与数据库连接的类。 And in MainActivity it is called as following: 在MainActivity中,它被称为如下:

MainActivity

public void onLogin(View view, String user, String pass){
    String type = "login";
    BackgroundWorker backgroundWorker = new BackgroundWorker(this);
    backgroundWorker.execute(type,user,pass);
}

Calling of function: 调用功能:

        loginbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String username = user_edittext.getText().toString();
            String password = pass_edittext.getText().toString();
            onLogin(v,username,password);


        }
    });

In short I want to return the variable result or tresult from protected void onPostExecute(String result) in my MainActivity and convert it to Array. 简而言之,我想从我的MainActivity protected void onPostExecute(String result)返回变量result或tresult,并将其转换为Array。 Thankyou! 谢谢! waiting for experts opinion. 等待专家意见。

It seems you have two issues: 看来你有两个问题:

  1. Converting a Json string to a more friendly format 将Json字符串转换为更友好的格式
  2. Returning this friendly format to another activity 将此友好格式返回到另一个活动

on 1: There is no built in way to parse JSON strings in Java but lots of easy library options available - take a look at How to parse JSON in Java where these are discussed. 1:没有内置的方法来解析Java中的JSON字符串,但是有很多简单的库选项可用 - 看看如何解析Java中的JSON

on 2: In general data is converted to a bundle and returned to your main activity as part of the intent system on 2:通常,数据会转换为捆绑并作为意向系统的一部分返回到主活动

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM