0

I have a fragment coontain costume listview.. when I login to my application I open the connection and get the data that should be stored in the listview, SOMETIMES the application crash

the connection is opened and get the code (200) but nothing return in body, I guess it would happen as it large data!?... my connection code is in asynctask I paste the link at the end of the question

I got this in my logcat

06-22 00:35:39.353 32052-32052/com.example.pc_orbit.myapplication D/AbsListView﹕ unregisterIRListener() is called

06-22 00:35:39.833 32052-32052/com.example.pc_orbit.myapplication D/result﹕ 200

06-22 00:35:39.833 32052-32052/com.example.pc_orbit.myapplication D/AndroidRuntime﹕ Shutting down VM

06-22 00:35:39.833 32052-32052/com.example.pc_orbit.myapplication W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x411ae930)

06-22 00:35:39.843 32052-32052/com.example.pc_orbit.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main android.os.NetworkOnMainThreadException

at com.example.pc_orbit.myapplication.WebServiceAsyncTask.onPostExecute( WebServiceAsyncTask.java:91)

atcom.example.pc_orbit.myapplication.WebServiceAsyncTask.onPostExecute( WebServiceAsyncTask.java:20)

this error WebServiceAsyncTask.onPostExecute( WebServiceAsyncTask.java:91)
 in the **connection** code

Feeds Fragment

public class Feeds extends Fragment implements OnServiceCompleted {
TextView name;
TextView description;
EditText comment;
Button post;
String namej;
String descriptionj;
String time, date, picture;
List<FeedRecord> records;
String data = "";
View view;
time t;
Connection connection= new Connection();
public static final String PREFS_NAME = "MyPrefsFile";
static SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
String emailSharedPref;
FeedListAdapter feedListAdapter;
ListView lv;

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    view = inflater.inflate(R.layout.feeds, container, false);
    sharedPreferences = this.getActivity().getSharedPreferences(PREFS_NAME, 0);
    editor = sharedPreferences.edit();
    emailSharedPref = sharedPreferences.getString("email", "");
    Log.e("Feeds in","");
    records = new ArrayList<>();

    selectFeeds();
/////////////////////////////////// comment
    t = new time();

    comment = (EditText) view.findViewById(R.id.comment);
    post = (Button) view.findViewById(R.id.post);
    post.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            date= t.date();
            time= t.time();
            String commentString = comment.getText().toString();
            JSONObject jsonObject = new JSONObject();
            if (connection.isConnectedToInternet(getActivity())) {
                URLPath urlPath = new URLPath();

                String serverURL = urlPath.addFeedback;
                WebServiceRequest request = new WebServiceRequest();
                request.setUrl(serverURL);
                try {
                    jsonObject.put("comment", commentString);
                    jsonObject.put("date", date);
                    jsonObject.put("time", time);
                    jsonObject.put("email", emailSharedPref);
                    Log.e("comment", jsonObject.toString());

                } catch (JSONException e) {
                    e.printStackTrace();
                }
                request.setRequestBody(jsonObject);
                WebServiceAsyncTask webService = new WebServiceAsyncTask(getActivity().getApplicationContext(), Feeds.this);
                WebServiceRequest[] requestArr = {request};
                webService.execute(requestArr);


                Toast toast = Toast.makeText(getActivity(), jsonObject.toString(), Toast.LENGTH_LONG);
                toast.show();
                comment.setText(" ");
                feedListAdapter.clear();
                selectFeeds();
            }
            else {
                Log.e("False","");
                Toast toast= Toast.makeText(getActivity().getApplicationContext(),"no connection",Toast.LENGTH_LONG);
                toast.show();
            }
        }
    });


    return view;
}

void selectFeeds() {
    Log.e("select feeds function","");
    if (connection.isConnectedToInternet(getActivity().getApplicationContext())) {
        Log.e("select feeds function connection","");

        URLPath urlPath = new URLPath();
        String serverURL = urlPath.showFeedback;
        WebServiceRequest request = new WebServiceRequest();
        request.setUrl(serverURL);

        WebServiceAsyncTask webService = new WebServiceAsyncTask(getActivity().getApplicationContext(), Feeds.this);
        WebServiceRequest[] requestArr = {request};
        webService.execute(requestArr);
    }
    else {
        Log.e("False","");
        Toast toast= Toast.makeText(getActivity().getApplicationContext(),"no connection, can't select feeds ",Toast.LENGTH_LONG);
        toast.show();
    }
}

@Override
public void onTaskCompleted(String result) {
    Toast.makeText(getActivity().getApplicationContext(), "getting Feeds", Toast.LENGTH_LONG).show();
    data = result;
    jsonarray(result);
    Log.e("5arag mel function", result);
}

void jsonarray(String arrayData) {
    try {
        Log.e("dataaaa", arrayData);

        JSONArray jArray = new JSONArray(arrayData);
        System.out.println("*****JARRAY*****" + jArray.length());
        for (int i = 0; i < jArray.length(); i++) {
            JSONObject json_data = jArray.getJSONObject(i);
            namej = json_data.getString("firstname") + " " + json_data.getString("lastname");
            descriptionj = json_data.getString("description");
            date = json_data.getString("date");
            time = json_data.getString("time");
            picture = json_data.getString("photo");
            Log.e("alll", namej + descriptionj + date + time + picture);
            Log.e("json Array function FEEDS ","");

            records.add(new FeedRecord(namej, descriptionj, picture));
        }
    } catch (JSONException e) {
        Toast toast= Toast.makeText(getActivity().getApplicationContext(),"stop2",Toast.LENGTH_SHORT);
        toast.show();
        Log.e("stop2","");
//            Intent intent= new Intent(getActivity(),Feeds.class);
//            startActivity(intent);
    }


    feedListAdapter = new FeedListAdapter(getActivity(), R.layout.feedrecord, records);
    lv = (ListView) view.findViewById(R.id.lv);
    lv.setAdapter(feedListAdapter);

    lv.deferNotifyDataSetChanged();
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            name = (TextView) view.findViewById(R.id.name);
            String nameS = name.getText().toString();
            description = (TextView) view.findViewById(R.id.description);

            String descriptionS = description.getText().toString();
            Log.e("feeddata",nameS+""+descriptionS);

            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
            // set title
            alertDialogBuilder.setTitle(nameS);
            // set dialog message
            alertDialogBuilder
                    .setMessage(descriptionS)
                    .setCancelable(false)
                    .setNegativeButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });
            AlertDialog alertDialog = alertDialogBuilder.create();  // create alert dialog
            alertDialog.show();
        }
    });

}

}

Feed List Adapter

public class FeedListAdapter extends ArrayAdapter<FeedRecord> {
LayoutInflater mInflater;
Context context;
TextView name;
ImageView img;
TextView description;
private List<FeedRecord> items = new ArrayList<FeedRecord>();
String names,descriptions,imgs;
private TextView description1;

public FeedListAdapter(Context context, int resource, List<FeedRecord> items) {
    super(context, resource, items);
    this.context = context;
    this.items=items;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
     if (null == convertView) {


        RelativeLayout view = (RelativeLayout) RelativeLayout.inflate(this.context,
                R.layout.feedrecord, null);
        Log.d("feed list adapter", "printing...");
        name =  new TextView(view.getContext());
        description1 = new TextView(view.getContext());


        view.addView(name);
        view.addView(description1);
        ImageView img = new ImageView(view.getContext());

        Picasso.with(getContext()).load(this.items.get(position).getImg()).resize(250, 250).into(img, new Callback() {

            @Override
            public void onSuccess() {
                Log.e("feed picsucess", "");
            }

            @Override
            public void onError() {
                Log.e("feed picfalse :3", "");
            }
        });
        convertView= view;
    }

        RelativeLayout view = (RelativeLayout) convertView;
        img=(ImageView)view.getChildAt(0);
        name = (TextView) view.getChildAt(1);
        description1 = (TextView) view.getChildAt(2);

        name.setText(this.items.get(position).getName());
        description1.setText(this.items.get(position).getDescription());

        Picasso.with(getContext()).load(this.items.get(position).getImg()).resize(250, 250).into(img, new Callback() {

            @Override
            public void onSuccess() {
                Log.e("feed pic2 sucess", "");
            }

            @Override
            public void onError() {
                Log.e("feed pic2 false :3", "");
            }
        });
    names =this.items.get(position).getName();
    descriptions =this.items.get(position).getDescription();

    return convertView;

}
}

Connection Code

public class WebServiceAsyncTask extends AsyncTask<WebServiceRequest, Void, WebserviceResponse> {
Context context;
OnServiceCompleted listener;

public WebServiceAsyncTask(Context context, OnServiceCompleted listener) {
    this.context = context;
    this.listener = listener;
}

public WebServiceAsyncTask() {

}


protected void onPreExecute() {

}

// Call after onPreExecute method
protected WebserviceResponse doInBackground(WebServiceRequest... urls) {
    WebserviceResponse serviceResult = null;

    // Defined URL  where to send data
    try {

        int resCode;
        String text;
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = null;
        String url = urls[0].getUrl();
        JSONObject urlBody = urls[0].getRequestBody();
        if (urlBody != null) {         // to set json object
            HttpPost postRequest = new HttpPost(url);
            //request.setHeader("Accept", "application/json");
            postRequest.setHeader("Content-type", "application/json");

            StringEntity entity = new StringEntity(urlBody.toString());
            postRequest.setEntity(entity);
            response = httpClient.execute(postRequest);
        } else {   // there is no json object
            HttpGet getRequest = new HttpGet(url);
            response = httpClient.execute(getRequest);
        }



        resCode = response.getStatusLine().getStatusCode();
        serviceResult = new WebserviceResponse();
        serviceResult.setResultCode(resCode); // get code=200
        serviceResult.setResult(response); // responce with json or done

    } catch (Exception e) {
        Log.e("error", e.toString());
    }
    return serviceResult;
}

protected void onPostExecute(WebserviceResponse result) {
    Log.e("result", "" + result.getResultCode());

    if (result.getResultCode() == 200) {

        //Toast.makeText(context, result.getResult().getStatusLine().getStatusCode() + "", Toast.LENGTH_LONG).show();
        BufferedReader in = null;
        try {
            in = new BufferedReader(new InputStreamReader(result.getResult().getEntity().getContent()));

            String line = "";
            StringBuffer returnFromServer = new StringBuffer();

            while ((line = in.readLine()) != null) {
                returnFromServer.append(line);
            }

            Log.e("return ", new String(returnFromServer));
            //Toast what we got from server
            if (listener != null) {
                listener.onTaskCompleted(returnFromServer.toString());
            }

        } catch (IOException e) {
            Log.e("error", e.toString());
        }
    }
}
}


public class WebServiceRequest {
String url;
JSONObject requestBody;

public String getUrl() {
    return url;
}

public void setUrl(String url) {
    this.url = url;
}

public JSONObject getRequestBody() {
    return requestBody;
}

public void setRequestBody(JSONObject requestBody) {
    this.requestBody = requestBody;
}
}

public class WebserviceResponse {

int resultCode;
HttpResponse result;

public int getResultCode() {
    return resultCode;
}

public void setResultCode(int resultCode) {
    this.resultCode = resultCode;
}

public HttpResponse getResult() {
    return result;
}

public void setResult(HttpResponse result) {
    this.result = result;
}
}

public interface OnServiceCompleted {
    void onTaskCompleted(String result);
 }

Here is My Connection Code

============================

@all who make comments,, Do you mean that I perform it in this way? EDIT

class FeedList extends AsyncTask<String, Void, Void> {

    private Exception exception;

    protected void   doInBackground(String... urls) {
        try {
            Log.e("select feeds function","");
            if (connection.isConnectedToInternet(getActivity().getApplicationContext())) {
                Log.e("select feeds function connection","");

                URLPath urlPath = new URLPath();
                String serverURL = urlPath.showFeedback;
                WebServiceRequest request = new WebServiceRequest();
                request.setUrl(serverURL);

                WebServiceAsyncTask webService = new WebServiceAsyncTask(getActivity().getApplicationContext(), Feeds.this);
                WebServiceRequest[] requestArr = {request};
                webService.execute(requestArr);
            }
            else {
                Log.e("False","");
                Toast toast= Toast.makeText(getActivity().getApplicationContext(),"no connection, can't select feeds ",Toast.LENGTH_LONG);
                toast.show();
            }
        } catch (Exception e) {
            this.exception = e;
      //     return null;
        }
     }

    protected void onPostExecute() {
        // TODO: check this.exception
        // TODO: do something with the feed
    }
}

Check the syntax please

Community
  • 1
  • 1
Aya Radwan
  • 181
  • 5
  • 17
  • do you mean that i should call the "selectFeeds()" function in async task??? this function have the connection code – Aya Radwan Jun 21 '15 at 23:06
  • ".NetworkOnMainThreadException" - you're accessing the network on the main thread, use an AsyncTask or Volley etc. – Zain Jun 21 '15 at 23:07
  • my connection code already in an asynctask! , should I make other asynctask in the fragment ?? – Aya Radwan Jun 21 '15 at 23:08
  • 1
    Seems like you are running network i\o in `onPostExecute`which is run on the main thread. – M4rtini Jun 21 '15 at 23:09
  • The error says otherwise. Somewhere you are attempting to access the network from the main UI thread. You need to figure out where and fix it. Start by looking at the error message. – Code-Apprentice Jun 21 '15 at 23:10
  • 1
    Post the code for .WebServiceAsyncTask - the error says you're trying to access network in onPostExecute - line 91. – Zain Jun 21 '15 at 23:10
  • @Zain :) first the error in the connection code, I updated so you can check it .. Second the connection code works with me for along of time.. I don't know what is the problem of my code :'( this hapnning sometimes especially when I returning too much data #HELP ! :( – Aya Radwan Jun 21 '15 at 23:22
  • @Code-Apprentice how can I fix it? would you please explain it to me?? :) – Aya Radwan Jun 22 '15 at 00:06
  • @Code-Apprentice please check the edit of the end of my post,, I preform it in asynctask,, please correct it to me :) – Aya Radwan Jun 22 '15 at 01:54
  • Are you still getting the same error? Or is it a different one? Can you post the log? – Zain Jun 22 '15 at 06:29
  • @Zain please correct my code the feed list class, i'm not sure that I wrote it write – Aya Radwan Jun 22 '15 at 08:57
  • from this link http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception I didn't use the asynctask,, I found the second answer using StrictMode ! and it works with me – Aya Radwan Jun 22 '15 at 11:29
  • If you are still getting the same error, please tell us where line 91 is in `WebServiceAsyncTask.java`. – Code-Apprentice Jun 24 '15 at 17:43
  • no i'm not getting any errors thank you – Aya Radwan Jun 25 '15 at 11:27

0 Answers0