I've been working on an Android project where I want to show all the data those are stored in the database. I've done that part already but the problem is I'm able to get the data from localhost but when I move to the hosted server it is not giving me any data. I've connected to the server and am able to access the specific php file but it is returning an empty JSON string where there are a of data.
Here is my Connection Class:
public class Connecter {
public static HttpURLConnection connect (String urlAddress){
try {
URL url = new URL(urlAddress);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
///////Setting properties to con object
con.setRequestMethod("POST");
con.setConnectTimeout(20000);
con.setReadTimeout(20000);
con.setDoInput(true);
con.setDoOutput(true);
////////Returning the Con object
return con;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
I'm posting using another class. And here is the process I'm using to pass the url of the specific php file:
String address2 = "http://www.tutorshubbd.com/android/allTeacher.php";
Log.d(TAG," .............///..........Primary Data Display ");
String query = "";
SendGetAllTeachers sg2 = new SendGetAllTeachers(ActivityTeacher.this,address2,query,listViewTeachers,ivNoData,ivNoInternet);
sg2.execute();
Here is the specific php file that I'm using:
<?php
$host ='tutorshubbd.com';
$username = 'cpanel_username';
$pwd = 'cpanel_password';
$db = 'tutorshu_db';
$con = mysqli_connect($host, $username, $pwd, $db) or die('Unable to connect');
if (mysqli_connect_error($con)) {
echo "Failed to connect to the DataBase".mysqli_connect_error();
}
$name = $_POST['Query'];
$sql = "SELECT * FROM Teacher WHERE Name LIKE '%$name%'";
$query = mysqli_query($con, $sql);
if ($query) {
while ($row = mysqli_fetch_array($query)) {
$data[] = $row;
}
print(json_encode($data));
}else{
echo "Not Found!";
}
mysqli_close($con);
?>
Here is some additional code where I'm posting and fetching data. (I'm having no trouble fetching data from localhost using this code but putting this just because if you need to see it to figure out the issue).
public class SendGetAllTeachers extends AsyncTask<Void,Void,String> {
private static final String TAG ="ActivityTeacher";
private Context context;
private String urlAddress;
private String query;
private ListView listView;
private ImageView imageViewNoData, imageViewNoSignal;
private ProgressDialog progressDialog;
public SendGetAllTeachers(Context context, String urlAddress, String query, ListView listView, ImageView...imageViews) {
this.context = context;
this.urlAddress = urlAddress;
this.query = query;
this.listView = listView;
this.imageViewNoData=imageViews[0];
this.imageViewNoSignal=imageViews[1];
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Search:");
progressDialog.setMessage("Searching for Data...");
progressDialog.show();
}
@Override
protected String doInBackground(Void... params) {
return this.sendAndReceive();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
//RESET LISTVIEW
listView.setAdapter(null);
if (s != null){
if (!s.contains("null")){
ParserTeacher parserT = new ParserTeacher(context,s,listView);
parserT.execute();
imageViewNoData.setVisibility(View.INVISIBLE);
imageViewNoSignal.setVisibility(View.INVISIBLE);
}else{
Log.d(TAG,"......//////////.........///////// Getting Visible ......... NO DATA______AT");
Toast.makeText(context, "Sorry! No Such Data Exists.", Toast.LENGTH_SHORT).show();
}
}else {
imageViewNoData.setVisibility(View.INVISIBLE);
Toast.makeText(context, "Sorry! Unable to connect to the server.", Toast.LENGTH_SHORT).show();
imageViewNoSignal.setVisibility(View.INVISIBLE);
}
}
private String sendAndReceive(){
HttpURLConnection con = Connecter.connect(urlAddress);
if(con == null)
return null;
try {
OutputStream outputStream = con.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
Log.d(TAG,"......//////////.........///////// WRITING DATA ......... FIRED______");
bufferedWriter.write(new DataPackager(query).packageData());
Log.d(TAG,"......//////////.........///////// NOT WORKING___!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
bufferedWriter.flush();
//Release Resources.
bufferedWriter.close();
outputStream.close();
//Response Code
int responseCode = con.getResponseCode();
//Decoding response code
if (responseCode == con.HTTP_OK){
//Return Data
InputStream inputStream = con.getInputStream();
//Read the returned data...
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
Log.d(TAG,"......//////////.........///////// DATA READ......... FIRED______");
StringBuffer response = new StringBuffer();
if (bufferedReader!=null){
while((line = bufferedReader.readLine())!=null){
response.append(line+"\n");
}
}else
return null;
return response.toString();
}else
return String.valueOf(responseCode);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
////////////////////////////////
public class DataPackager {
String query;
public DataPackager(String query) {
this.query = query;
}
public String packageData(){
JSONObject jsonObject = new JSONObject();
StringBuffer queryStringBuffer = new StringBuffer();
try {
jsonObject.put("Query", query);
Boolean fistValue = true;
Iterator iterator = jsonObject.keys();
do {
String key = iterator.next().toString();
String value = jsonObject.get(key).toString();
if (fistValue){
fistValue = false;
}else{
queryStringBuffer.append("&");
}
queryStringBuffer.append(URLEncoder.encode(key,"UTF-8"));
queryStringBuffer.append("=");
queryStringBuffer.append(URLEncoder.encode(value,"UTF-8"));
}while (iterator.hasNext());
return queryStringBuffer.toString();
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
}
///////////////////////////////
public class ParserTeacher extends AsyncTask<Void,Void,Integer> {
public static final String TAG = "Parser Teacher";
private Context c;
private String data;
private ListView lv;
List<GetItems> items = new ArrayList<>();
public ParserTeacher(Context c, String data, ListView lv) {
this.c = c;
this.data = data;
this.lv = lv;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Integer doInBackground(Void... params){
return this.parse();
}
@Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if (integer ==1 ){
///////BIND TO LIST VIEW...............................
CustomAdapter adapter = new CustomAdapter(c, items);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
GetItems sendItem = items.get(i);
String name = sendItem.getName();
//Snackbar.make(view,"Teachers Detail Mode",Snackbar.LENGTH_LONG).show();
Intent I = new Intent();
I.setClass(view.getContext(),TeachersView.class);
Bundle extras = new Bundle();
extras.putString("Name", name);
I.putExtras(extras);
view.getContext().startActivity(I);
}
});
}else{
Log.d(TAG," >>>>>>>>>>>>>>>>>>>>>>>>>>>> Parsing Error!");
Toast.makeText(c, "Unable to Parse...!", Toast.LENGTH_SHORT).show();
}
}
private int parse(){
try{
JSONArray ja = new JSONArray(data);
//Log.i("tagconvertstr","............................................\n\n"+ "["+ja+"]");
JSONObject jo = null;
items.clear();
GetItems getItems = null;
for (int i=0; i<ja.length();i++){
jo=ja.getJSONObject(i);
String name = jo.getString("Name");
getItems = new GetItems();
getItems.setName(name);
items.add(getItems);
}
return 1;
} catch (JSONException e) {
Log.d(TAG,"Here is the STACK TRACE.........>>>>>>>>>>>>>>>>>>>>>>>>>>>");
e.printStackTrace();
}
return 0;
}
}
(I'm having no trouble fetching data in localhost using this code).
if you load the url you will see that there are a lot of data(could take time to load sometimes) but in the app It is returning an empty string. I'm not using any libraries like volley or retrofit.
I've seen a lot of issues regarding this but this is slightly different from them. I'm being able to connect but not fetch from hosted server but I'm able to fetch from local host.
but it is returning an empty JSON string
Is it? But please start at the begin. What issendAndReceive()
returning?null
? Which Toast do you see in onPostExecute? You could give some helpfull info about what happens!if(con == null) return null;
. That is not very informative. How would you know that it was this null if it happened?Toast.makeText(context, "Sorry! No Such Data Exists.", Toast.LENGTH_SHORT).show(); }
. You are not showing the contents of s. Change toToast.makeText(context, "Sorry! No Such Data Exists: "+s, Toast.LENGTH_SHORT).show(); }
if (!s.contains("null"))
would come true and the parser invoked. You would certainly not see the Sorry toast.