在Android Studio中获取并显示JSON对象

时间:2016-07-31 11:13:45

标签: android json android-studio

我知道这里有很多类似的问题,但我没有找到任何解决方案,因为案例都略有不同。我是android编程的新手,需要通过PHP将数据从SQL获取到Android应用程序中。现在,无论我尝试什么教程或代码,我都会遇到错误。这是我尝试过的最简单的方法,只需在PHP中获取一个JSON对象(工作正常,它在浏览器中显示)并将其放在我的应用程序中的TextView中。但它一直在崩溃,我不知道我需要改变什么。

这是PHP代码(“meinprofil.php”):

 <meta charset="utf-8">
<?php
        include("../config/config.php");

        $mail = 'em@fh.de';
        $abfrage = mysql_query("SELECT * FROM user WHERE user_mail LIKE '".$mail."'") or die(mysql_error());
        $user = mysql_fetch_array($abfrage);

    $profil = array('id' => $user['id_user'], 'name' => $user['user_name'], 'mail' => $user['user_mail'], 'tel' => ['user_tel']);

        echo json_encode($profil);
        $json = $profil;
        return $json; ?>

这是ProfilAnsicht.java类:

package com.example.android.festivalapp;

import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import org.json.JSONArray;
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.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

//Main Klasse
public class Profil extends StartseiteNachLogin {


    ImageView iVProfilbild;
    EditText eTUserAlter;
    Button bProfilAendern;
    TextView tvUsername1;

    //Layoutverknüpfung
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.profil);

        iVProfilbild = (ImageView) findViewById(R.id.iVProfilbild);
        tvUsername1 = (TextView) findViewById(R.id.tvUsername);
        eTUserAlter = (EditText) findViewById(R.id.eTUserAlter);
        bProfilAendern = (Button) findViewById(R.id.bProfilAendern);

        new JSONTask().execute("http://pou-pou.de/stagedriver/android/meinprofil.php");


    }

    public class JSONTask extends AsyncTask<String, String, String> {
        @Override
        protected String doInBackground(String... params) {

            HttpURLConnection connection = null;
            BufferedReader reader = null;
            try {
                URL url = new URL(params[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();

                InputStream stream = connection.getInputStream();

                reader = new BufferedReader(new InputStreamReader(stream));
                StringBuffer buffer = new StringBuffer();
                String line = "";

                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
                String finalJson = buffer.toString();
                JSONObject parentObject = new JSONObject(finalJson);
                JSONArray parentArray = parentObject.getJSONArray("profil");
                JSONObject finalObject = parentArray.getJSONObject(0);

                String user_name = finalObject.getString("name");

                return user_name;

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
                try {
                    if (reader != null) {
                        reader.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            TextView tvUsername;
            tvUsername = (TextView) findViewById(R.id.tvUsername);
            tvUsername.setText(result);
        }
    }
}

当我运行它时,我收到以下错误:

07-31 12:25:20.314 31348-31348/com.example.android.festivalapp W/System: ClassLoader referenced unknown path: /data/app/com.example.android.festivalapp-1/lib/arm64
07-31 12:25:20.488 31348-31348/com.example.android.festivalapp W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
07-31 12:25:20.572 31348-31413/com.example.android.festivalapp D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
07-31 12:25:20.596 31348-31413/com.example.android.festivalapp I/Adreno: QUALCOMM build                   : bf7710d, I0bc8e21cf2
                                                                         Build Date                       : 03/09/16
                                                                         OpenGL ES Shader Compiler Version: XE031.06.00.02
                                                                         Local Branch                     : 
                                                                         Remote Branch                    : quic/LA.BF64.1.2.2_rb4.28
                                                                         Remote Branch                    : NONE
                                                                         Reconstruct Branch               : NOTHING
07-31 12:25:20.599 31348-31413/com.example.android.festivalapp I/OpenGLRenderer: Initialized EGL, version 1.4
07-31 12:25:20.690 31348-31348/com.example.android.festivalapp I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@7000656 time:118876554
07-31 12:25:35.764 31348-31348/com.example.android.festivalapp I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@7000656 time:118891628
07-31 12:25:37.619 31348-31348/com.example.android.festivalapp W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
07-31 12:25:38.605 31348-31348/com.example.android.festivalapp I/Timeline: Timeline: Activity_launch_request id:com.example.android.festivalapp time:118894469
07-31 12:25:38.729 31348-31684/com.example.android.festivalapp I/DpmTcmClient: RegisterTcmMonitor from: com.android.okhttp.TcmIdleTimerMonitor
07-31 12:25:38.804 31348-31684/com.example.android.festivalapp W/System.err: org.json.JSONException: **Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject**
07-31 12:25:38.804 31348-31684/com.example.android.festivalapp W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
07-31 12:25:38.804 31348-31684/com.example.android.festivalapp W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:160)
07-31 12:25:38.804 31348-31684/com.example.android.festivalapp W/System.err:     at org.json.JSONObject.<init>(JSONObject.java:173)
07-31 12:25:38.804 31348-31684/com.example.android.festivalapp W/System.err:     at com.example.android.festivalapp.Profil$JSONTask.doInBackground(Profil.java:68)
07-31 12:25:38.804 31348-31684/com.example.android.festivalapp W/System.err:     at com.example.android.festivalapp.Profil$JSONTask.doInBackground(Profil.java:47)
07-31 12:25:38.804 31348-31684/com.example.android.festivalapp W/System.err:     at android.os.AsyncTask$2.call(AsyncTask.java:295)
07-31 12:25:38.804 31348-31684/com.example.android.festivalapp W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
07-31 12:25:38.804 31348-31684/com.example.android.festivalapp W/System.err:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
07-31 12:25:38.804 31348-31684/com.example.android.festivalapp W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
07-31 12:25:38.804 31348-31684/com.example.android.festivalapp W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
07-31 12:25:38.804 31348-31684/com.example.android.festivalapp W/System.err:     at java.lang.Thread.run(Thread.java:818)
07-31 12:25:38.860 31348-31413/com.example.android.festivalapp D/OpenGLRenderer: endAllActiveAnimators on 0x5561e47040 (ListPopupWindow$DropDownListView) with handle 0x5561e8f2d0
07-31 12:25:38.865 31348-31348/com.example.android.festivalapp I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@1d1f9b0 time:118894728
07-31 12:29:07.316 31348-31348/com.example.android.festivalapp I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@7000656 time:119103180

如果有人能提供帮助我真的很感激。我已经在这里阅读了很多问题和教程,但我仍然不理解将PHP与JSON连接到Java并获取要显示的JSON对象/数组的基本方法。如果somone知道我需要遵循的“食谱”或基本步骤,如果你与我分享,我会非常感激!

提前致谢!

1 个答案:

答案 0 :(得分:0)

我怀疑你必须将php代码修改为

$enc_value = json_encode($profil);
return $enc_value;

因为否则结果不会以json格式编码。事实上,从Java方面你可以删除:

JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("profil");
JSONObject finalObject = parentArray.getJSONObject(0);

仅使用:

JSONObject finalObject = new JSONObject(finalJson);