Yomal Amarathunge
Yomal Amarathunge

Reputation: 125

Nothing shows on TextViews when parsing JSON(Randomy generated) from Url; (Java,Android)

I am writing an android app to get data from a database using JSON. PHP file is written to give random data from the database table. This file is working. This is my php.

<?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);
 
?>
When I get this JSON array.

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

(This is randomly generated)

So I wrote following code to show questionSin and answer as Question and Answer in two text views. Following are my two .java files

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

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;

}
  }

This is my xml file

<?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 Studio do not show any error of my code. When I installed .apk in my phone, app runs, but nothing shows on textViews. Please help me. Thank you.

Upvotes: 1

Views: 64

Answers (1)

Bapusaheb Shinde
Bapusaheb Shinde

Reputation: 849

Change

private static final String ARRAY = "results";

To

private static final String ARRAY = "result";

key mismatch: actual : "result"

you are providing wrong ie "results"

Upvotes: 3

Related Questions