【问题标题】:can't fetch data from mysql database with json file in android studio无法在android studio中使用json文件从mysql数据库中获取数据
【发布时间】:2018-02-28 23:56:22
【问题描述】:

我的 android 应用程序无法从数据库中获取值并显示在 ListView.customers_mysql.php 在浏览器中工作。您可以在浏览器中查看结果。我的应用程序工作正常,我认为我的 php 文件不正确。 请帮帮我。

customers_mysql.php

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

$conn = new mysqli("*****", "*****", "*****", "******");

$result = $conn->query("SELECT CompanyName, City, Country FROM Customers");


while($rs = $result->fetch_array(MYSQLI_ASSOC)) {

    $Name = $rs["CompanyName"];
    $City = $rs["City"];
    $Country = $rs["Country"];
    $posts[] = array('Name'=> $Name, 'City'=> $City, 'Country'=> $Country);
}
//$response['posts'] = $posts;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($posts));
fclose($fp);
$conn->close();
echo json_encode($posts);


?>

MainActivity.java

package com.example.khan_pti.mfetchdata;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;


public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button b = (Button)findViewById(R.id.button);
        b.setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getBaseContext(),Fetch.class));
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Fetch.java

package com.example.khan_pti.mfetchdata;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.HttpURLConnection;
import java.util.ArrayList;

/**
 * Created by khan-pti on 30/03/2015.
 */
public class Fetch extends Activity {
    ArrayList<Flowers> flowersList = new ArrayList<Flowers>();
    String url ="http://yakhforosh.skyf.ir/customers_mysql.php";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fetch);


        new BackTask().execute(url);
    }

    public class BackTask extends AsyncTask<String,String,String>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... strings) {
             String content =HttpULRConnect.getData(url);
            return content;
        }

        @Override
        protected void onPostExecute(String s) {
            try {


            JSONArray ar = new JSONArray(s);
            for (int i=0; i<ar.length(); i++){
                JSONObject jsonobject = ar.getJSONObject(i);
                Flowers  flowers = new Flowers();
                flowers.setName(jsonobject.getString("City"));

                flowersList.add(flowers);

            }
            }
            catch (JSONException e){
                e.printStackTrace();
            }
            FlowerAdapter adapter = new FlowerAdapter(Fetch.this, R.layout.flowers_list_items, flowersList);
            ListView lv = (ListView) findViewById(R.id.listView);
            lv.setAdapter(adapter);
           //Log.d("recived",s);


        }
    }

}

Fetch.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">



    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

HttpULRConnect.java

package com.example.khan_pti.mfetchdata;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by khan-pti on 30/03/2015.
 */
public class HttpULRConnect {
    public static String getData(String uri){

        BufferedReader reader = null;
        try {

            URL url = new URL(uri);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            StringBuilder sb = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            Log.d("testhtt2","test");
            String line;
            while ((line= reader.readLine())!=null) {

                sb.append(line+"\n");


            }
            Log.d("test44", sb.toString());
            return sb.toString();


        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return null;
        }
        finally{

            if (reader!=null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    return null;
                }

            }
        }}}

Flowers.java

package com.example.khan_pti.mfetchdata;

/**
 * Created by khan-pti on 30/03/2015.
 */
public class Flowers {
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    private String name;

}

FlowerAdapter.java

package com.example.khan_pti.mfetchdata;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by khan-pti on 01/04/2015.
 */
public class FlowerAdapter extends ArrayAdapter<Flowers> {
    private  ArrayList<Flowers> items;
    private Context mContext;
    public FlowerAdapter(Context context, int textViewResourceID, ArrayList<Flowers> items){
        super(context,textViewResourceID,items);
        mContext = context;
        this.items = items;

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View v = convertView;
        Flowers flowers = items.get(position);
        if(v==null){
            LayoutInflater inflater =(LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v=inflater.inflate(R.layout.flowers_list_items,null);

        }
        TextView title = (TextView)v.findViewById(R.id.textView3);
        if (title != null) {
            title.setText(flowers.getName());
        }
        return v;
    }
}

flowers_list_items.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/textView3" />
</LinearLayout>

清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.khan_pti.mfetchdata" >
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Fetch"></activity>
    </application>

</manifest>

和我的 android 日志 wheb 运行应用程序

09-20 08:39:39.891 24773-24773/com.example.khan_pti.mfetchdata I/art: Not late-enabling -Xcheck:jni (already on)
09-20 08:39:40.073 24773-24773/com.example.khan_pti.mfetchdata W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.khan_pti.mfetchdata-2/split_lib_dependencies_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.khan_pti.mfetchdata-2@split_lib_dependencies_apk.apk@classes.dex) because non-0 exit status
09-20 08:39:40.307 24773-24773/com.example.khan_pti.mfetchdata W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.khan_pti.mfetchdata-2/split_lib_slice_0_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.khan_pti.mfetchdata-2@split_lib_slice_0_apk.apk@classes.dex) because non-0 exit status
09-20 08:39:40.346 24773-24773/com.example.khan_pti.mfetchdata W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.khan_pti.mfetchdata-2/split_lib_slice_1_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.khan_pti.mfetchdata-2@split_lib_slice_1_apk.apk@classes.dex) because non-0 exit status
09-20 08:39:40.391 24773-24773/com.example.khan_pti.mfetchdata W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.khan_pti.mfetchdata-2/split_lib_slice_2_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.khan_pti.mfetchdata-2@split_lib_slice_2_apk.apk@classes.dex) because non-0 exit status
09-20 08:39:40.443 24773-24773/com.example.khan_pti.mfetchdata W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.khan_pti.mfetchdata-2/split_lib_slice_3_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.khan_pti.mfetchdata-2@split_lib_slice_3_apk.apk@classes.dex) because non-0 exit status
09-20 08:39:40.511 24773-24773/com.example.khan_pti.mfetchdata W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.khan_pti.mfetchdata-2/split_lib_slice_4_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.khan_pti.mfetchdata-2@split_lib_slice_4_apk.apk@classes.dex) because non-0 exit status
09-20 08:39:40.560 24773-24773/com.example.khan_pti.mfetchdata W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.khan_pti.mfetchdata-2/split_lib_slice_5_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.khan_pti.mfetchdata-2@split_lib_slice_5_apk.apk@classes.dex) because non-0 exit status
09-20 08:39:40.603 24773-24773/com.example.khan_pti.mfetchdata W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.khan_pti.mfetchdata-2/split_lib_slice_6_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.khan_pti.mfetchdata-2@split_lib_slice_6_apk.apk@classes.dex) because non-0 exit status
09-20 08:39:40.635 24773-24773/com.example.khan_pti.mfetchdata W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.khan_pti.mfetchdata-2/split_lib_slice_7_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.khan_pti.mfetchdata-2@split_lib_slice_7_apk.apk@classes.dex) because non-0 exit status
09-20 08:39:40.677 24773-24773/com.example.khan_pti.mfetchdata W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.khan_pti.mfetchdata-2/split_lib_slice_8_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.khan_pti.mfetchdata-2@split_lib_slice_8_apk.apk@classes.dex) because non-0 exit status
09-20 08:39:40.713 24773-24773/com.example.khan_pti.mfetchdata W/art: Failed execv(/system/bin/dex2oat --runtime-arg -classpath --runtime-arg  --debuggable --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2 --runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/app/com.example.khan_pti.mfetchdata-2/split_lib_slice_9_apk.apk --oat-file=/data/dalvik-cache/x86/data@app@com.example.khan_pti.mfetchdata-2@split_lib_slice_9_apk.apk@classes.dex) because non-0 exit status
09-20 08:39:40.714 24773-24773/com.example.khan_pti.mfetchdata W/System: ClassLoader referenced unknown path: /data/app/com.example.khan_pti.mfetchdata-2/lib/x86
09-20 08:39:40.721 24773-24773/com.example.khan_pti.mfetchdata I/InstantRun: starting instant run server: is main process
09-20 08:39:41.005 24773-24831/com.example.khan_pti.mfetchdata D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true

                                                                                 [ 09-20 08:39:41.010 24773:24773 D/         ]
                                                                                 HostConnection::get() New Host Connection established 0xab5c20c0, tid 24773


                                                                                 [ 09-20 08:39:41.069 24773:24831 D/         ]
                                                                                 HostConnection::get() New Host Connection established 0xab5c2880, tid 24831
09-20 08:39:41.076 24773-24831/com.example.khan_pti.mfetchdata I/OpenGLRenderer: Initialized EGL, version 1.4
09-20 08:39:41.166 24773-24773/com.example.khan_pti.mfetchdata W/art: Before Android 4.1, method int android.support.v7.internal.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
09-20 08:39:44.907 24773-24888/com.example.khan_pti.mfetchdata D/testhtt2: test
09-20 08:39:44.919 24773-24888/com.example.khan_pti.mfetchdata D/test44: <html><body><script type="text/javascript" src="/aes.js" ></script><script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("457d15ccad5389221d0935d83ac973ce");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="http://yakhforosh.skyf.ir/customers_mysql.php?i=1";</script><noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript></body></html>
09-20 08:39:44.935 24773-24831/com.example.khan_pti.mfetchdata E/Surface: getSlotFromBufferLocked: unknown buffer: 0xaeff1000
09-20 08:39:44.946 24773-24831/com.example.khan_pti.mfetchdata D/OpenGLRenderer: endAllStagingAnimators on 0xb30a1b80 (RippleDrawable) with handle 0xaefd2d20
09-20 08:39:44.974 24773-24773/com.example.khan_pti.mfetchdata W/System.err: org.json.JSONException: Value <html><body><script of type java.lang.String cannot be converted to JSONArray
09-20 08:39:44.974 24773-24773/com.example.khan_pti.mfetchdata W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
09-20 08:39:44.974 24773-24773/com.example.khan_pti.mfetchdata W/System.err:     at org.json.JSONArray.<init>(JSONArray.java:96)
09-20 08:39:44.974 24773-24773/com.example.khan_pti.mfetchdata W/System.err:     at org.json.JSONArray.<init>(JSONArray.java:108)
09-20 08:39:44.974 24773-24773/com.example.khan_pti.mfetchdata W/System.err:     at com.example.khan_pti.mfetchdata.Fetch$BackTask.onPostExecute(Fetch.java:52)
09-20 08:39:44.974 24773-24773/com.example.khan_pti.mfetchdata W/System.err:     at com.example.khan_pti.mfetchdata.Fetch$BackTask.onPostExecute(Fetch.java:34)
09-20 08:39:44.975 24773-24773/com.example.khan_pti.mfetchdata W/System.err:     at android.os.AsyncTask.finish(AsyncTask.java:651)
09-20 08:39:44.975 24773-24773/com.example.khan_pti.mfetchdata W/System.err:     at android.os.AsyncTask.-wrap1(AsyncTask.java)
09-20 08:39:44.975 24773-24773/com.example.khan_pti.mfetchdata W/System.err:     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
09-20 08:39:44.975 24773-24773/com.example.khan_pti.mfetchdata W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
09-20 08:39:44.975 24773-24773/com.example.khan_pti.mfetchdata W/System.err:     at android.os.Looper.loop(Looper.java:148)
09-20 08:39:44.976 24773-24773/com.example.khan_pti.mfetchdata W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
09-20 08:39:44.976 24773-24773/com.example.khan_pti.mfetchdata W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
09-20 08:39:44.976 24773-24773/com.example.khan_pti.mfetchdata W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
09-20 08:39:44.976 24773-24773/com.example.khan_pti.mfetchdata W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

【问题讨论】:

  • 检查脚本返回的内容,根据错误:org.json.JSONException: Value
  • 我无法返回 json 值

标签: php android sql json database


【解决方案1】:

查看错误消息,您似乎得到的是对实际网址的重定向。您的网络调用返回一个包含文本 location.href="http://yakhforosh.skyf.ir/customers_mysql.php?i=1 的 html 页面,当直接访问此 url 时,我得到一个 JSON 响应。

您应该尝试更改您尝试访问的网址或在您的HTTPUrlConnection 上调用setFollowsRedirects(true)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    相关资源
    最近更新 更多