0

I am very new at this. I have already read and watch and try a lot tutorials, but I can't find something very easy in order to understand how it works.

I have made a php file where you can see the results of o form "result.php". In the form, you can insert the First-name and Last-name. Those are saved in the database.

In "result.php", you can see the results as:

{"nametable":[{"fname":"","lname":""},{"fname":"ni","lname":"gi"}]}

Now, I would like to find an easy way, in order to understand it, were on my Android code, there is going to be just a text view and show the first name.. I don't want to get confused with buttons, just a page where is going to show a variable from a database!

Is there anyone that can help me with code, in order to understand the way it works??

Thank you!!

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
ni gi
  • 75
  • 1
  • 10

1 Answers1

0

Here's a simple code sample I made, using org.json library & OkHttp client.

It will retrieve the JSON from the server, and show every first name in TextViews.

Note: I didn't test it, it may not compile, but you get the idea.

activity_main.xml

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

    <!-- TextView's will be appended here -->

</LinearLayout>

MyActivity.java

//...other imports

import org.json.*;
import okhttp3.*;

public class MyActivity extends AppCompatActivity {

   private LinearLayout textViewWrapper;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      //Get TextView Wrapper
      textViewWrapper = (LinearLayout) findViewById(R.id.textViewWrapper);

      fillTextView();
   }

   /**
    *    Fill TextViews with API response.
    *
    */

   public void fillTextView() {

      get("http://example.com/result.php", new Callback() {
         @Override
         public void onFailure(Call call, IOException e) {}

         @Override
         public void onResponse(Call call, final Response response) throws IOException {

            final String body = response.body().string(); //Get API response

            //OKHttp callback isn't in the main thread, 
            //UI operations need to be run in the main thread
            //That's why you should use runOnUiThread
            MyActivity.this.runOnUiThread(new Runnable() {
               @Override
               public void run() {

                  JSONObject JSON = null;
                  try {
                     //Parse JSON
                     JSON = new JSONObject(body);
                     //Get "nametable" array
                     JSONArray nameTable = JSON.getJSONArray("nametable");
                     //Loop through "nametable" array
                     for (int i = 0; i < nameTable.length(); i++) {

                        JSONObject item = nameTable.getJSONObject(i);

                        //Create TextView
                        TextView rowTextView = new TextView(MyActivity.this);

                        //Set fname
                        rowTextView.setText(item.getString("fname"));

                        // add the textview
                        textViewWrapper.addView(rowTextView);
                     }

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

   }

   /**
    *   OKHttp GET helper function (You should probably put this in a Request Utils class)
    *
    */

   public Call get(String url, Callback callback) {

      OkHttpClient client = new OkHttpClient();

      okhttp3.Request request = new okhttp3.Request.Builder()
         .url(url)
         .get()
         .build();

      Call call = client.newCall(request);
      call.enqueue(callback);

      return call;

   }
}

More info on parsing JSON in this question: How to parse JSON in Java

Community
  • 1
  • 1
Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98
  • Thank you for your response and sorry for my delay!! I would like to ask you some details in order to try and run it!! First of all, I have my first error on "import okhttp3.*;" It says that cannot resolve symbol... Next, there is missing the library for new Callback(). The problem is that there are soooo many options to choose to import with alt+enter and I don't know witch is the proper.. could you help me?? I think that when "new Callback()" some of the next problems will be disappear.. Could you help me in order to proceed with my code?? Thank you!! :) – ni gi Feb 21 '16 at 10:07
  • You need to install the library. Add the dependency to your gradle. `compile 'com.squareup.okhttp3:okhttp:3.1.2'` Check the link I provide for okhttp. – Marcos Casagrande Feb 21 '16 at 15:45