-1

I just need help with a situation where i have to load data from remote server and i am using volley library for the purpose of fetching the values from the server so this is what i have done so far

public class Leaderboard extends AppCompatActivity {
private ListView leaderListView;
private ProgressDialog loading;
private TextView myname,myrank,myaccu;
public static final String ROOT_URL = "http://thehostels.in/judgement_files/";

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

    myname=(TextView)findViewById(R.id.myname);
    myrank=(TextView)findViewById(R.id.myrank);
    myaccu=(TextView)findViewById(R.id.myAccuracy);
    getMe();


}

 User user = SharedPrefManager.getInstance(Leaderboard.this).getUser();
 String userEmail= user.getEmail();

public void getMe(){


        loading = ProgressDialog.show(this,"","",false,false);
        String url = Config.Leaderboard.toString().trim();


        StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                loading.dismiss();
                showJSON(response);
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        loading.dismiss();
                    }
                });

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

private void showJSON(String response){
    String textname="";
    String textrank="";
    String textacc="";
    String val1="";
    String val2="";


    try {
        JSONObject jsonObject = new JSONObject(response);
        JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY_Leader);
        JSONObject TeamData = result.getJSONObject(0);
        textname = TeamData.getString(Config.myname);
        textrank = TeamData.getString(Config.myrank);
        textacc = TeamData.getString(Config.myaccuracy);
        val1=("#"+textrank+".");
        val2=(textacc+"%");

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

    myrank.setText(val1);
    myname.setText(textname);
    myaccu.setText(val2);
}

   public void sendEmail(){


    RestAdapter adapter = new RestAdapter.Builder()
            .setEndpoint(ROOT_URL) //Setting the Root URL
            .build(); //Finally building the adapter

    //Creating object for our interface
    myEmail api = adapter.create(myEmail.class);

    //Defining the method insertuser of our interface
    api.sendMail(

            userEmail,
            //Creating an anonymous callback
            new Callback<retrofit.client.Response>() {
                @Override
                public void success(retrofit.client.Response result, retrofit.client.Response response) {
                    //On success we will read the server's output using bufferedreader
                    //Creating a bufferedreader object
                    BufferedReader reader = null;

                    //An string to store output from the server
                    String output = "";

                    try {
                        //Initializing buffered reader
                        reader = new BufferedReader(new InputStreamReader(result.getBody().in()));

                        //Reading the output in the string
                        output = reader.readLine();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    //Displaying the output as a toast
                    Toast.makeText(Leaderboard.this, output, Toast.LENGTH_LONG).show();


                }

                @Override
                public void failure(RetrofitError error) {
                    //If any error occured displaying the error as toast
                    Toast.makeText(Leaderboard.this, "something went wrong", Toast.LENGTH_LONG).show();
                }
            }
    );
}

and config.java file

public class Config {
    public static final String Leaderboard = "http://thehostels.in/judgement_files/myleaderboard.php";
    public static final String myname = "name";
    public static final String myrank = "rank";
    public static final String myaccuracy = "accuracy";
    public static final String JSON_ARRAY_Leader= "list";
    }

myleaderboard.php

<?php
  if($_SERVER['REQUEST_METHOD']=='POST'){
     $email=$_POST['userEmail'];
      define('HOST','xxxxxxxx');
      define('USER','xxxxxxxx');
      define('PASS','xxxxxxxx');
      define('DB','xxxxxxxx');

      $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');

      $sql = "select * from Leaderboard where email='$email'";

      $res = mysqli_query($con,$sql);
      $result = array();
      while($row = mysqli_fetch_array($res)){
      array_push($result,
      array('name'=>$row[1],
      'rank'=>$row[2],
      'accuracy'=>$row[3]));
       }
      echo json_encode (array("list"=>$result));
        }
       mysqli_close($con);

        }
           ?>

my json returns me

  {"list":[{"name":"Vipul S","rank":"1","accuracy":"80"}]}

main file which contains textviews leaderboard.xml

        <RelativeLayout 
     xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="3sp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

<funplay.dreamstar1.CustomTextView
    android:layout_marginLeft="10sp"
    android:layout_marginStart="10sp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="@color/black"
    android:text="#1"
    android:layout_marginTop="20sp"
    android:textSize="17sp"
    android:id="@+id/myrank"/>

<funplay.dreamstar1.CustomTextView
    android:layout_marginLeft="35sp"
    android:layout_marginStart="35sp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="@color/black"
    android:text="Vipul S"
    android:layout_marginTop="20sp"
    android:textSize="17sp"
    android:id="@+id/myname"/>

<funplay.dreamstar1.CustomTextView
    android:layout_marginEnd="12sp"
    android:layout_marginRight="12sp"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="@color/black"
    android:text="100%"
    android:layout_marginTop="20sp"
    android:textSize="17sp"
    android:id="@+id/myAccuracy"/>

so the thing is MySQL table contains many columns and i just wanna retrieve few columns from that table and encode in json to get it back to my android code but somehow it is not happening and data is not populating in textview and i have debug the PHP code its working all fine.

here sendEmail function is used to send email from android to myleaderboard.php file which then only chooses the row with matching email so i just wanna know what is problem over here or is there any alternative way to do so....

Prakash
  • 1
  • 6
  • Just to get clarity of the scenario. You aren't seeing the result of these 3 statements right? `myrank.setText(val1); myname.setText(textname); myaccu.setText(val2);`. Did you ensure through debugging that `val1, val2` and `textname` are populated before setting it to these textviews? – LeoNeo Dec 24 '17 at 06:34
  • yes of course... – Prakash Dec 24 '17 at 06:38
  • can you share your xml file contents where the listview and textviews are present – LeoNeo Dec 24 '17 at 06:39
  • i have added the xml file, is that ok for informations needed to get the things done @LeoNeo – Prakash Dec 24 '17 at 07:11
  • The xml has funplay.dreamstar1.CustomTextView while you are initializing the variables as TextView. The CustomTextView is important in the context of this issue, this is something you should have mentioned and provided the code for in the first place. :) Are you sure your CustomTextView code isn't the culprit here? Coz we don't know what is going on inside the class. – LeoNeo Dec 24 '17 at 07:18
  • actually i have initialized all my textviews like that and i have used custom textview in xml file and never any issue occured thats for sure, even when make http calls , so the issue is not that... – Prakash Dec 24 '17 at 07:27
  • btw i just wanted to tell you that when i load my activity, it implements sendEmail function which then send my email address which is stored in the shared preferences to myleaderboard.php and it returns json (i have mentined ) as output but when i try to use that output as json object and make a json array of it, it says that its not a perfect json...@LeoNeo – Prakash Dec 24 '17 at 07:31
  • **when i try to use that output as json object and make a json array of it, it says that its not a perfect json** This statement would mean that your variables val1, val2 and textname would not get populated, since if the . You mentioned that the variables are getting populated as you expect them to be. That would mean one of these lines or the 3 lines after that should throw an error : `JSONObject jsonObject = new JSONObject(response); JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY_Leader); JSONObject TeamData = result.getJSONObject(0);` – LeoNeo Dec 24 '17 at 10:58
  • well i think because there is a problemn with my php file actually i want to fetch data based on where clause and i m using seperate method to set the value for where thats the reason it is not able to perform so just tell me how to make json based on where clause becuase i don't want to print all columns in my listview, i just wanted to retrieve few columns based on email.. – Prakash Dec 24 '17 at 11:08
  • If you have issues with the where clause then you'll need to post the SQL query and the table structure along with what data are you are intending to pull up from the database. – LeoNeo Dec 24 '17 at 13:04

1 Answers1

0

Given below is the json you are getting back from your php. (I am not well versed in php to suggest any errors in your php code. But since you claim that the php code is working all fine and returning the json you want / expect.)

{
    "list": [
        {
            "name": "Vipul S",
            "rank": "1",
            "accuracy": "80"
        }
    ]
}

create the following two classes

public class MyPhpResponse {
    private List<MyPhpObject> list;

    public List<MyPhpObject> getList() {
        return list;
    }

    public void setList(List<MyPhpObject> inputList) {
        list = inputList;
    }
}

public class MyPhpObject {
    private String name;
    private String rank;
    private String accuracy;

    public String getName() {
        return name;
    }

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

    public String getRank() {
        return rank;
    }

    public void setRank(String rank) {
        this.rank = rank;
    }

    public String getAccuracy() {
        return accuracy;
    }

    public void setAccuracy(String accuracy) {
        this.accuracy = accuracy;
    }
}

Now use the Google's Gson library https://mvnrepository.com/artifact/com.google.code.gson/gson/2.8.2 and do the following in your showJSON method :

private void showJSON(String response) {
        try {
            final Gson gson = new Gson();
            final MyPhpResponse myPhpResponse = gson.fromJson(response, MyPhpResponse.class);
            //Assuming you are getting only one object back in the list
            final MyPhpObject myPhpObject = myPhpResponse.getList().get(0);
            myrank.setText(myPhpObject.getRank());
            myname.setText(myPhpObject.getName());
            myaccu.setText(myPhpObject.getAccuracy());
        } catch (MalformedJsonException e) {
            e.printStackTrace();
        }
    }

This should expose any issues with the JSON and if there are no issues the TextView should definitely show the data. Let me know how it works out for you.

LeoNeo
  • 739
  • 1
  • 9
  • 28
  • yes json is not right actually , the main issue is that email variable of php file is dynamically changing so i need any thing like this answer [link](https://stackoverflow.com/questions/34555236/retrieve-mysql-data-using-where-clauses) ,i think this is what i am looking for and it suits my situation more... – Prakash Dec 24 '17 at 13:44
  • you know my condition so i request you to guide me over that answer in my case – Prakash Dec 24 '17 at 13:46
  • I am trying to guide you but I need a proper explanation from your end to understand what the exact issue is. You mentioned the JSON was correct and the issue was with the textviews and now we discover that the json isn't right. Did you not pick up the JSON in your question from the debugger on android? that's what I expected it was. and that json looks good. Did you take the json from the response that php is sending to your android? or is it just a template of the json that you are *expecting*. – LeoNeo Dec 24 '17 at 16:15