Issue
I’m trying to learn android recycleview.
I followed some tutorial to fetch mysql data and display it in recycleview.
Here is the tutorial explained in code:
https://demonuts.com/android-json-parsing-and-display-with-recyclerview/
Everything works fine but he is not mentioning how did he parse Mysql table to Json.
I tried to create sama table with same json responses but recycleview is not fetching data.
Here is my Parsing php:
<?php
$arr = array();
//open connection to mysql db
$connection = mysqli_connect("xxx", "xxx", "xxx", "xxx") or die("Error " . mysqli_error($connection));
$sql = "select * from mytable";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$data = array('status' => 'true', 'message' => 'Data fetched successfully!');
while($row = mysqli_fetch_assoc($result))
{
$data['data'][] = $row;
}
$info = json_encode($data, JSON_PRETTY_PRINT);
echo '<pre>'; print_r($info);
//close the db connection
mysqli_close($connection);
?>
It retuens json table same as his table but data still not showing in recycleview!
I overrided Json reponses by declaring an array in the header with status and message then encoded it and it passed Json response in recycleview but still no data fetched!
I’m missing something about php and json encoding!
main_activity of the tutorial:
package com.example.parsaniahardik.json_recyclerview_zerone;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
private String jsonURL = "https://sarahah.plus/conn.php";
private final int jsoncode = 1;
private RecyclerView recyclerView;
ArrayList<RogerModel> rogerModelArrayList;
private RogerAdapter rogerAdapter;
private static ProgressDialog mProgressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler);
fetchJSON();
}
@SuppressLint("StaticFieldLeak")
private void fetchJSON(){
showSimpleProgressDialog(this, "Loading...","Fetching Json",false);
new AsyncTask<Void, Void, String>(){
protected String doInBackground(Void[] params) {
String response="";
HashMap<String, String> map=new HashMap<>();
try {
HttpRequest req = new HttpRequest(jsonURL);
response = req.prepare(HttpRequest.Method.POST).withData(map).sendAndReadString();
} catch (Exception e) {
response=e.getMessage();
}
return response;
}
protected void onPostExecute(String result) {
//do something with response
Log.d("newwwss",result);
onTaskCompleted(result,jsoncode);
}
}.execute();
}
public void onTaskCompleted(String response, int serviceCode) {
Log.d("responsejson", response.toString());
switch (serviceCode) {
case jsoncode:
if (isSuccess(response)) {
removeSimpleProgressDialog(); //will remove progress dialog
rogerModelArrayList = getInfo(response);
rogerAdapter = new RogerAdapter(this,rogerModelArrayList);
recyclerView.setAdapter(rogerAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));
}else {
Toast.makeText(MainActivity.this, getErrorCode(response), Toast.LENGTH_SHORT).show();
}
}
}
public ArrayList<RogerModel> getInfo(String response) {
ArrayList<RogerModel> tennisModelArrayList = new ArrayList<>();
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.getString("status").equals("true")) {
JSONArray dataArray = jsonObject.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
RogerModel playersModel = new RogerModel();
JSONObject dataobj = dataArray.getJSONObject(i);
playersModel.setName(dataobj.getString("name"));
playersModel.setCountry(dataobj.getString("country"));
playersModel.setCity(dataobj.getString("city"));
playersModel.setImgURL(dataobj.getString("imgURL"));
tennisModelArrayList.add(playersModel);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return tennisModelArrayList;
}
public boolean isSuccess(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
if (jsonObject.optString("status").equals("true")) {
return true;
} else {
return false;
}
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
public String getErrorCode(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
return jsonObject.getString("message");
} catch (JSONException e) {
e.printStackTrace();
}
return "No data";
}
public static void removeSimpleProgressDialog() {
try {
if (mProgressDialog != null) {
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
mProgressDialog = null;
}
}
} catch (IllegalArgumentException ie) {
ie.printStackTrace();
} catch (RuntimeException re) {
re.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void showSimpleProgressDialog(Context context, String title,
String msg, boolean isCancelable) {
try {
if (mProgressDialog == null) {
mProgressDialog = ProgressDialog.show(context, title, msg);
mProgressDialog.setCancelable(isCancelable);
}
if (!mProgressDialog.isShowing()) {
mProgressDialog.show();
}
} catch (IllegalArgumentException ie) {
ie.printStackTrace();
} catch (RuntimeException re) {
re.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Solution
first think make sure you are sending the correct header by putting this on top of your file :
header('Content-Type: application/json');
then debug your final array and make sure everything is ok and data coming as expected by using :
var_dump($data);die();
then hit this endpoint by postman or any web browser to see the result and make sure its working well .
if everything goes well and work as expected,remove the last line and simply return $data array
return json_encode($data);
the complete code should be like this:
<?php
header('Content-Type: application/json');
$arr = array();
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
//open connection to mysql db
$connection = mysqli_connect("xxx", "xxx", "xxx", "xxx");
$sql = "select * from mytable";
$result = mysqli_query($connection, $sql);
//create an array
$data = array('status' => 'true', 'message' => 'Data fetched successfully!');
while ($row = mysqli_fetch_assoc($result)) {
$data['data'][] = $row;
}
return json_encode($data);
Answered By – Moussab Kbeisy
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0