2017-08-10 4 views
1

JSONを使用してデータベースからデータを取得するアンドロイドアプリを作成しています。 PHPファイルは、データベーステーブルからランダムなデータを与えるために書かれています。このファイルは動作しています。これは私のPHPです。URLからJSON(Randomy generated)を解析するときにTextViewsに何も表示されません。 (Java、Android)

<?php 
 
define('HOST','localhost'); 
 
define('USER','*********'); 
 
define('PASS','*********'); 
 
define('DB','*********'); 
 
$con = mysqli_connect(HOST,USER,PASS,DB); 
 

 
$sql="SELECT `id`, `questionSin`,`answer` FROM `tf_questions` ORDER BY RAND() LIMIT 1"; 
 
    
 

 
$res = mysqli_query($con,$sql); 
 
    
 
$result = array(); 
 
    
 
while($row = mysqli_fetch_array($res)){ 
 
array_push($result, 
 
array('id'=>$row[0], 
 
'questionSin'=>$row[1], 
 
'answer'=>$row[2] 
 
)); 
 
} 
 
    
 
echo json_encode(array("result"=>$result),JSON_UNESCAPED_UNICODE); 
 
    
 
mysqli_close($con); 
 
    
 
?>
私は、このJSON配列を取得します。

{"result":[{"id":"13","questionSin":"KO2<\/sub>වල O පරමාණුවේ ඔක්සිකරණ අංකය -2 වේ.","answer":"T"}]} 

(これはランダムに生成される)

だから私は質問としてquestionSin答えを示し、2つのテキストビューに答えるために、次のコードを書きました。 後はMainActivity.java

package com.example.android.myjson; 

import android.os.AsyncTask; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 

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

public class MainActivity extends AppCompatActivity { 
TextView question_view; 
TextView answertf_view; 
Button Btngetdata; 


//URL to get JSON Array 
private static String url = "https://symbolistic-gyros.********.php"; 

//JSON Node Names 
private static final String QUESTION_SIN = "questionSin"; 
private static final String ANSWER = "answer"; 
private static final String ARRAY = "results"; 


JSONArray user = null; 



@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    setContentView(R.layout.activity_main); 
    Btngetdata = (Button)findViewById(R.id.true_button); 
    Btngetdata.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      new JSONParse().execute(); 
     } 
    }); 







} 



private class JSONParse extends AsyncTask<String, String, JSONObject> { 

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

    } 

    @Override 
    protected JSONObject doInBackground(String... args) { 
     JSONParser jParser = new JSONParser(); 

     // Getting JSON from URL 
     JSONObject json = jParser.getJSONFromUrl(url); 
     return json; 
    } 
    @Override 
    protected void onPostExecute(JSONObject json) { 

     try { 
      // Getting JSON Array 
      user = json.getJSONArray(ARRAY); 
      JSONObject c = user.getJSONObject(0); 

      // Storing JSON item in a Variable 
      String questionSin = c.getString(QUESTION_SIN); 
      String answertf1 = c.getString(ANSWER); 

      question_view = (TextView)findViewById(R.id.question); 
      answertf_view = (TextView)findViewById(R.id.answer); 



      //Set JSON Data in TextView 
      question_view.setText(questionSin); 
      answertf_view.setText(answertf1); 



     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 


    } 
} 

    } 

JSONParser.java私の2 の.javaファイル

ある

package com.example.android.myjson; 

import android.util.Log; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.methods.HttpPost; 
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; 

/** 
* Created by Yomal Amarathunge on 8/9/2017. 
    */ 

public class JSONParser { 

static InputStream is = null; 
static JSONObject jObj = null; 
static String json = ""; 

// constructor 
public JSONParser() { 

} 

public JSONObject getJSONFromUrl(String url) { 

    // Making HTTP request 
    try { 
     // defaultHttpClient 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost(url); 

     HttpResponse httpResponse = httpClient.execute(httpPost); 
     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; 

} 
    } 

これは私のXMLファイルです

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:app="http://schemas.android.com/apk/res-auto" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:orientation="vertical" 
android:layout_height="match_parent" 
    tools:context="com.example.android.myjson.MainActivity"> 



<TextView 
    android:id="@+id/question" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:padding="16dp" 

    /> 

<TextView 
    android:id="@+id/answer" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:padding="16dp" 

    /> 

<LinearLayout 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal"> 
    <Button 
     android:id="@+id/true_button" 
     android:layout_width="0dp" 
     android:layout_height="match_parent" 
     android:layout_weight="0.27" 
     android:text="True" /> 


</LinearLayout> 



</LinearLayout> 

Androidスタジオは自分のコードのエラーを表示しません。私の電話機に.apkをインストールすると、アプリケーションは動作しますが、textViewsには何も表示されません。 私を助けてください。ありがとうございました。

+0

を提供している私は、Androidマニフェストにインターネットのアクセス権を追加しましたまた、 –

+0

メソッドのチェーンに沿った実際の戻り値を確認しましたか? 'json = sb.toString();'と 'String questionSin = c.getString(QUESTION_SIN);'の実際の値は? – Barns

+0

一般的には、あなたの 'onCreate()'メソッドに対して、 'question_view =(TextView)findViewById(R.id.question);と' answertf_view =(TextView)findViewById(R.id.answer); – Barns

答えて

3

変更

private static final String ARRAY = "results"; 

private static final String ARRAY = "result"; 

への鍵の不一致:実際: "結果"

あなたは間違っている、すなわち "結果"

+2

優れた作品!それは私が勤勉と呼ぶものです! – Barns

+0

はい、それは私の間違いでした。主な問題は解決されました。しかし、そのテキストをUNICODEにエンコードするには、そのことに言及してください。ありがとうございました 。@Bapusaheb –

+0

文字列new_string = Html.fromHtml(your_unicode_here); –

関連する問題