receiving data from web server doesn't work (volley library android)
Asked Answered
S

1

7

For fetch data I use volley library. When i use Local Address everything work right. My activity shows data.

String json_url = "http://192.168.1.4/android/contactinfo.php";

but when I fetch data from Web server (internet) my activity doesn't show anything, so it is empty without any error

 String json_url = "http://www.viratebco.com/phpme/3/1.php";

I compared the output of these two pages and they were exactly like each other. this is my php code

    <?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);

and this is my class for fetch data of server

   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;
    }
}

My MySingleton class

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);
    }


}

My actorList Page

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);

        }
    }


}

My app works right but just when i fetch data from local services.

Syblesybley answered 26/8, 2017 at 17:10 Comment(11)
Change the file extension name "contactinfo.php" to "contactinfo.json" then try hope it will work.Goop
if I change the extension file.I will not have any output.i use php servise'sSyblesybley
@pedramshabani did you tried to change Request.Method.POST to get method?Lurk
i did and no result again...:-(Syblesybley
I didn't find any problem in your code except that BackgrundTask.getList() returning arrayList, Could you please check if it is returning blank ArrayList which is assigned to your RecyclerView Adapter and mayBe the reason for no data getting displayedMorningglory
@pedramshabani is ` Log.d("TAG67", response.toString()); ` printing/writing expected response in console ?Lurk
Mahmood Sanjrani:it is my consol: when run app in emalator ----->>> D/TAG67: [{"Name":"naseri","Pic":"http:\/\/www.viratebco.com\/phpme\/3\/actor3.jpg","Description":"در کل شرکت آمازون به‌دنبال ورود به‌ بخش‌های مختلفی از تجارت الکترونیک است و همچنین در زمینه به‌خدمت گرفتن دیگر شرکت‌ها و فروشگاه‌های اینترنتی هم دریغ نمی‌کند. "},{"Name":"soltani","Pic":"http:\/\/www.viratebco.com\/phpme\/3\/actor.jpg","Description":"gg"},{"Name":"shabnai","Pic":"http:\/\/www.viratebco.com\/phpme\/3\/actor4.jpg","Description":"hh"}]Syblesybley
D/Volley: [175] BasicNetwork.logSlowRequests: HTTP response for request=<[ ] viratebco.com/phpme/3/1.php 0xc4a84e57 NORMAL 1> [lifetime=5462], [size=579], [rc=200], [retryCount=0]Syblesybley
– Firoz Memon::I am guessing.my RecyclerView Adapter have not any problem because when i use Address Local (example:192.168.1.4/android/contactinfo.php))my app Works fine.Syblesybley
@pedramshabani I have updated my answer. which should resolve your problem.Mellicent
@pedramshabani Does the answer solve your question? Please See this image. Thanks.Slang
M
3

Update:

I checked your code everything was at it's place except listener.onReponseReceive(arrayList); as mentioned in my answer it should be right after where while loop ends. Now your recyclerview is displaying items

Update:

The reason You are not getting the list in your recyclerview is because it takes some time to fetch response from webserver and your list get return earlier. In order to Resolve this, Try this

Create an Interface

    public interface WebResponseListener{
     void onReponseReceive(ArrayList <Contact_actors_list> list);
   }

In your BackgrundTask declare a variable of this interface

WebResponseListener listener;
public BackgrundTask (Context context,WebResponseListener listener)
    {
       this.listener = listener
        this.context = context;
    }

Make your getList() return void and do the following changes

 public void getList(){
//Where your while condition ends
//add following line
  listener.onReponseReceived(arrayList);
    -----
}

IN actorsList class Make yout actorList class implements the inferface as

public class actorsList extends AppCompatActivity implements WebResponseListener

replace the following lines

BackgrundTask backgroundTask = new BackgrundTask(actorsList.this); 
 arrayList = backgroundTask.getList();

with

BackgrundTask backgroundTask = new BackgrundTask(this,this); 
arrayList = new ArrayList<>();
adapter = new RecyclerAdapterActorsList(arrayList);
recyclerView.setAdapter(adapter);
backgroundTask.getList();

Add the following method in your actorsList class

public void onReponseReceive(ArrayList <Contact_actors_list> list){
    actorsList.this.arrayList.addAll(list);
    actorsList.this.adapter.notifyDataSetChanged();
}

Recyclerview

Mellicent answered 2/9, 2017 at 19:29 Comment(6)
thank you Sahil Manchanda .now i have fetal error::->>> Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView$Adapter.notifyDataSetChanged()' on a null object referenceSyblesybley
at ir.gitta.www.successsecrets.actorsList.onReponseReceive(actorsList.java:71) at ir.gitta.www.successsecrets.BackgrundTask.getList(BackgrundTask.java:98) at ir.gitta.www.successsecrets.actorsList.onCreate(actorsList.java:62)Syblesybley
@pedramshabani Answer Updated. NullPointerException error occured because adapter was not initialized before calling getList() method.Mellicent
Sahil Manchanda :really thank you so much but actorList Does not show anything still.Syblesybley
Can you email me the project so that i can check. if possible or let me create a dummy projectMellicent
Let us continue this discussion in chat.Mellicent

© 2022 - 2024 — McMap. All rights reserved.