从 Web 服务器接收数据不起作用(volley library android)
Posted
技术标签:
【中文标题】从 Web 服务器接收数据不起作用(volley library android)【英文标题】:receiving data from web server doesn't work (volley library android) 【发布时间】:2018-02-04 11:23:02 【问题描述】:为了获取数据,我使用 volley 库。当我使用本地地址时,一切正常。我的活动显示数据。
String json_url = "http://192.168.1.4/android/contactinfo.php";
但是当我从 Web 服务器(互联网)获取数据时,我的活动没有显示任何内容,所以它是空的,没有任何错误
String json_url = "http://www.viratebco.com/phpme/3/1.php";
我比较了这两个页面的输出,它们完全一样。 这是我的php代码
<?php
error_reporting(0);
@ini_set('display_errors', 0);
$host="localhost";
$username="root";
$pwd="";
$db="android";
$con = mysqli_connect($host,$username,$pwd,$db) or die ('unable to connect');
mysqli_set_charset($con, "utf8");
$sql = "SELECT * FROM imageactor";
$result = mysqli_query($con,$sql);
$response = array();
while($row = mysqli_fetch_array($result))
array_push($response,array("Name"=>$row["name"],"Pic"=>$row["pic"],"Description"=>$row["description"]));
header("Connection: Keep-alive");
header("Content-length: 468");
header('Content-type: application/json');
echo json_encode($response,JSON_UNESCAPED_UNICODE);
这是我获取服务器数据的类
public class BackgrundTask
Context context;
ArrayList<Contact_actors_list> arrayList = new ArrayList<>();
String json_url = "http://192.168.1.4/phpme/3/1.php";
public BackgrundTask (Context context)
this.context = context;
public ArrayList<Contact_actors_list> getList()
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, json_url,(String) null,
new Response.Listener<JSONArray>()
@Override
public void onResponse(JSONArray response)
Log.d("TAG67", response.toString());
int count = 0;
while (count<response.length())
try
// Log.d("TAG67", "kk"+count);
JSONObject jsonObject = response.getJSONObject(count);
// Log.d("TAG67", "Pic "+jsonObject.getString("Pic"));
// Log.d("TAG67", "Description "+jsonObject.getString("Description"));
// Log.d("TAG67", "Name "+jsonObject.getString("Name"));
Contact_actors_list contact_actors_list = new Contact_actors_list(jsonObject.getString("Name"),jsonObject.getString("Pic"),jsonObject.getString("Description"));
Log.d("TssssssssAG67", contact_actors_list.getDescription());
arrayList.add(contact_actors_list);
count++;
catch (JSONException e)
e.printStackTrace();
Log.e("tageiu", "Error at sign in : " + e.getMessage());
, new Response.ErrorListener()
@Override
public void onErrorResponse(VolleyError error)
error.printStackTrace();
Log.e("ERtROR123", "Error123 "+ error.getMessage());
Log.d("ERtROR123", "Error123 "+ error.getMessage());
);
int x=4;// retry count
jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 48,
x, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getmInstance(context).addToRequestque(jsonArrayRequest);
return arrayList;
我的 MySingleton 类
public class MySingleton
private static MySingleton mInstance;
private RequestQueue requestQueue;
private static Context mCtx;
private MySingleton(Context context)
mCtx = context;
requestQueue = getRequestQueue();
public RequestQueue getRequestQueue()
if (requestQueue==null)
requestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
return requestQueue;
public static synchronized MySingleton getmInstance(Context context)
if (mInstance == null)
mInstance = new MySingleton(context);
return mInstance;
public <T> void addToRequestque(Request<T> request)
request.setRetryPolicy(new DefaultRetryPolicy(0, -1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
requestQueue.add(request);
我的演员列表页面
public class actorsList extends AppCompatActivity
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<Contact_actors_list> arrayList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_actors_list);
System.setProperty("http.keepAlive", "false");
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(actorsList.this, recyclerView ,new RecyclerItemClickListener.OnItemClickListener()
@Override public void onItemClick(View view, int position)
Intent intent = new Intent(actorsList.this, DetailsAsctor.class);
Contact_actors_list pp = arrayList.get(position);
intent.putExtra("pic", pp.getPic());
intent.putExtra("title", pp.getName());
startActivity(intent);
//Toast.makeText(actorsList.this,position,Toast.LENGTH_LONG).show();
@Override public void onLongItemClick(View view, int position)
Toast.makeText(actorsList.this,"click",Toast.LENGTH_LONG).show();
)
);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
BackgrundTask backgroundTask = new BackgrundTask(actorsList.this);
arrayList = backgroundTask.getList();
adapter = new RecyclerAdapterActorsList(arrayList);
recyclerView.setAdapter(adapter);
RecyclerAdapterActorsList
public class RecyclerAdapterActorsList extends RecyclerView.Adapter<RecyclerAdapterActorsList.MyViewHolder>
ArrayList<Contact_actors_list> arrayList = new ArrayList<>();
public RecyclerAdapterActorsList(ArrayList<Contact_actors_list> arrayList)
this.arrayList = arrayList;
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item_actors_list,parent,false);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
@Override
public void onBindViewHolder(MyViewHolder holder, int position)
holder.Name1.setText(arrayList.get(position).getName());
holder.Description1.setText(arrayList.get(position).getDescription());
Picasso.with(holder.Pic1.getContext()).load(Uri.parse(arrayList.get(position).getPic())).into(holder.Pic1);
@Override
public int getItemCount()
return arrayList.size();
public static class MyViewHolder extends RecyclerView.ViewHolder
TextView Name1;
TextView Description1;
ImageView Pic1;
public MyViewHolder(View itemView)
super(itemView);
Name1 = (TextView) itemView.findViewById(R.id.name);
Description1 = (TextView) itemView.findViewById(R.id.description);
Pic1 = (ImageView) itemView.findViewById(R.id.pic);
我的应用程序运行正常,但只是当我从本地服务获取数据时。
【问题讨论】:
将文件扩展名“contactinfo.php”更改为“contactinfo.json”然后尝试希望它会工作。 如果我更改扩展文件。我不会有任何输出。我使用 php servise 的 @pedramshabani 您是否尝试更改Request.Method.POST
以获取方法?
我做了,又没有结果...:-(
@pedramshabani 答案是否解决了您的问题?请See this image。谢谢。
【参考方案1】:
更新:
我检查了你的代码,除了 listener.onReponseReceive(arrayList);正如我的回答中提到的那样 应该在while循环结束的地方之后。现在你的回收站视图是 显示项目
更新:
您没有在回收站视图中获得列表的原因是 因为从网络服务器和您的服务器获取响应需要一些时间 列表获得更早的回报。为了解决这个问题,试试这个
创建接口
public interface WebResponseListener
void onReponseReceive(ArrayList <Contact_actors_list> list);
在你的BackgrundTask中声明这个接口的变量
WebResponseListener listener;
public BackgrundTask (Context context,WebResponseListener listener)
this.listener = listener
this.context = context;
使您的 getList() 返回 void 并进行以下更改
public void getList()
//Where your while condition ends
//add following line
listener.onReponseReceived(arrayList);
-----
IN 演员列表类 让你的actorList类实现接口为
public class actorsList extends AppCompatActivity implements WebResponseListener
替换下面几行
BackgrundTask backgroundTask = new BackgrundTask(actorsList.this);
arrayList = backgroundTask.getList();
与
BackgrundTask backgroundTask = new BackgrundTask(this,this);
arrayList = new ArrayList<>();
adapter = new RecyclerAdapterActorsList(arrayList);
recyclerView.setAdapter(adapter);
backgroundTask.getList();
在你的actorsList类中添加以下方法
public void onReponseReceive(ArrayList <Contact_actors_list> list)
actorsList.this.arrayList.addAll(list);
actorsList.this.adapter.notifyDataSetChanged();
【讨论】:
谢谢你 Sahil Manchanda。现在我有胎儿错误::->>> 原因:java.lang.NullPointerException: 尝试调用虚拟方法 'void android.support.v7.widget.RecyclerView$ Adapter.notifyDataSetChanged()' 在空对象引用上 在 ir.gitta.www.successsecrets.actorsList.onReponseReceive(actorsList.java:71) 在 ir.gitta.www.successsecrets.BackgrundTask.getList(BackgrundTask.java:98) 在 ir.gitta .www.successsecrets.actorsList.onCreate(actorsList.java:62) @pedramshabani 答案已更新。发生 NullPointerException 错误,因为在调用 getList() 方法之前没有初始化适配器。 Sahil Manchanda :非常感谢你,但 actorList 仍然没有显示任何内容。 你能把项目发邮件给我,我可以检查一下。如果可能的话,或者让我创建一个虚拟项目以上是关于从 Web 服务器接收数据不起作用(volley library android)的主要内容,如果未能解决你的问题,请参考以下文章
带有参数的 Volley jsonObjectRequest 不起作用
Android Volley 的 onResponse 方法未执行