我一直致力于Android项目,我希望在其中显示存储在数据库中的所有数据。我已经完成了那部分,但问题是我能够从 localhost 获取数据但是当我移动到托管服务器时它不是给我任何数据。我已连接到服务器并且能够访问特定的php文件,但它返回一个空的JSON字符串,其中包含数据。
这是我的连接类:
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;
}
}
我使用其他课程发帖。 这是我用来传递特定php文件的URL的过程:
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();
以下是我使用的特定php文件:
<?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);
?>
&#13;
以下是我发布和提取数据的其他代码。 (我在使用此代码从localhost获取数据时没有遇到任何问题,但这样做只是因为如果您需要查看它以找出问题)。
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;
}
}
(我使用此代码在localhost中获取数据没有问题。)
如果您加载网址,您会看到有很多数据(有时可能需要时间加载),但在应用程序中它返回一个空字符串。我没有使用像排球或翻新这样的任何库。
我已经看到很多关于此的问题,但这与它们略有不同。我能够连接但不能从托管服务器获取,但我能够从本地主机获取。
答案 0 :(得分:0)
您的回复标头没有Content-Type值。你必须在打印数据之前添加到你的php代码中。
header('Content-type:application/json;charset=utf-8');