NetworkOnMainThreadException occured even having AsyncTask - android-asynctask

I am new to Android app development. I have read several posts which suggest that I have to use AsyncTask to get into a PHP file and edit a database.
Here is my class with AsyncTask.
private class urlEditTask extends AsyncTask<Void, Void, Void>{
final String propName;
final String roomLoc;
final String roomType;
public urlEditTask(final String propName, final String roomLoc, final String roomType){
super();
this.propName = propName;
this.roomLoc = roomLoc;
this.roomType = roomType;
}
#Override
protected Void doInBackground(Void... params) {
editDB(propName, roomLoc, roomType);
return null;
}
protected void onPostExecute(Void... params) {
Toast.makeText(getApplicationContext(), "Loading....", Toast.LENGTH_LONG).show();
}
private void editDB(final String propName, final String roomLoc, final String roomType){
String name = etName.getText().toString();
String contact = etContact.getText().toString();
String email = etEmail.getText().toString();
String rentStart = etRentStart.getText().toString();
String rentEnd = etRentEnd.getText().toString();
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
nameValuePair.add(new BasicNameValuePair("name", name));
nameValuePair.add(new BasicNameValuePair("propName", propName));
nameValuePair.add(new BasicNameValuePair("roomLoc", roomLoc));
nameValuePair.add(new BasicNameValuePair("roomType", roomType));
nameValuePair.add(new BasicNameValuePair("contact", contact));
nameValuePair.add(new BasicNameValuePair("email", email));
nameValuePair.add(new BasicNameValuePair("rentStart", rentStart));
nameValuePair.add(new BasicNameValuePair("rentEnd", rentEnd));
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://hoome.hk/EditDB.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
String msg = "Data entered successfully";
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
Log.e("ClientProtocol", "Log_tag");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I want the task to be executed after I clicked a button.
Here is my code for execution.
Button confirmEdit = (Button) findViewByID(R.id.confirmEdit);
confirmEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new urlEditTask(itemValue1, itemValue2, itemValue3).execute();
}
});
Probably, I don't quite understand how AsyncTask works.
May I know why I get NetworkOnMainThreadException with the above codes?
Here is the log:
07-20 04:14:01.480 2588-2603/hk.hoome.www.contracthandler E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: hk.hoome.www.contracthandler, PID: 2588
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:336)
at android.widget.Toast.<init>(Toast.java:100)
at android.widget.Toast.makeText(Toast.java:250)
at hk.hoome.www.contracthandler.MainActivity$urlEditTask.doInBackground(MainActivity.java:443)
at hk.hoome.www.contracthandler.MainActivity$urlEditTask.doInBackground(MainActivity.java:399)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)    
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)

Related

JSON Array With Volley Showing Only One data

I am trying to display array data using JSON Volley in PostsBasedOnCategory.java. Array data that I want to display are, Title post, and excerpt based on specific category from https://www.kisahmuslim.com/wp-json/wp/v2/categories. But unfortunately, it only showing one result.
Below you can check my code
DaftarCategories.java
public class CallingPage extends AsyncTask<String, String, String> {
HttpURLConnection conn;
java.net.URL url = null;
private int page = 1;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
showNoFav(false);
pb.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... params) {
try {
url = new URL("https://www.kisahmuslim.com/wp-json/wp/v2/categories");
}
catch(MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return("koneksi gagal");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
protected void onPostExecute(String result)
{
JsonArrayRequest stringRequest = new JsonArrayRequest(Request.Method.GET, SumberPosts.HOST_URL+"wp/v2/categories/", null, new Response.Listener<JSONArray>()
{
#Override
public void onResponse(JSONArray response) {
// display response
Log.d(TAG, response.toString() + "Size: "+response.length());
// agar setiap kali direfresh data tidak redundant
typeForPosts.clear();
for(int i=0; i<response.length(); i++) { //ambil semua objek yang ada
final CategoriesModel post = new CategoriesModel();
try {
Log.d(TAG, "Object at " + i + response.get(i));
JSONObject obj = response.getJSONObject(i);
post.setId(obj.getInt("id"));
post.setPostURL(obj.getString("link"));
//Get category name
post.setCategory(obj.getString("name"));
//////////////////////////////////////////////////////////////////////////////////////
// getting article konten
JSONObject postCategoryParent = obj.getJSONObject("_links");
JSONArray postCategoryObj = postCategoryParent.getJSONArray("wp:post_type");
JSONObject postCategoryIndex = postCategoryObj.getJSONObject(0); //ambil satu objek saja
String postCategoryUrl = postCategoryIndex.getString("href"); //satu objek yang dimaksud adalah href
if(postCategoryUrl != null) {
Log.d(TAG, postCategoryIndex.getString("href"));
JsonArrayRequest getKonten = new JsonArrayRequest(Request.Method.GET, postCategoryUrl, null, new Response.Listener<JSONArray>()
{
#Override
public void onResponse(JSONArray respon) {
Log.d(TAG, respon.toString() + "Size: "+respon.length());
for(int d=0; d<respon.length(); d++) {
try {
//Log.d(TAG, "Object at " + i + respon.get());
JSONObject objek = respon.getJSONObject(d); //ambil semua artikel yang tersedia di postCategoryUrl
post.setId(objek.getInt("id"));
post.setCreatedAt(objek.getString("date"));
post.setPostURL(objek.getString("link"));
//Get category title
JSONObject titleObj = objek.getJSONObject("title");
post.setJudul(titleObj.getString("rendered"));
//Get excerpt
JSONObject exerptObj = objek.getJSONObject("excerpt");
post.setExcerpt(exerptObj.getString("rendered"));
// Get content
JSONObject contentObj = objek.getJSONObject("content");
post.setContent(contentObj.getString("rendered"));
}
catch (JSONException e) {
e.printStackTrace();
}
}// for category
} //onResponse2
}, new Response.ErrorListener() { //getKonten
#Override
public void onErrorResponse(VolleyError error) {
pb.setVisibility(View.GONE);
Log.d(TAG, error.toString());
}
});
queue.add(getKonten);
} //if postCategoryUrl
//////////////////////////////////////////////////////////////////////////////////////
typeForPosts.add(post);
} //try 1
catch (JSONException e) {
e.printStackTrace();
}
} //for 1
pb.setVisibility(View.GONE);
recycleViewWordPress.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
} //onResponse1
}, new Response.ErrorListener() { //stringRequest
#Override
public void onErrorResponse(VolleyError error) {
showNoFav(true);
pb.setVisibility(View.GONE);
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getContext(), "Tidak bisa menampilkan data. Periksa kembali sambungan internet Anda", Toast.LENGTH_LONG).show();
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
} //onPostExecute
} //CallingPage
#Override
public void onPostingSelected(int pos) {
CategoriesModel click = typeForPosts.get(pos);
excerpt = click.getExcerpt();
//gambar = click.getPostImg();
judul = click.getJudul();
//url = click.getPostURL();
content = click.getContent();
Bundle bundle = new Bundle();
bundle.putString("judul", judul);
//bundle.putString("gambar", gambar);
//bundle.putString("url", url);
bundle.putString("content", content);
bundle.putString("excerpt", excerpt);
PostsBasedOnCategory bookFragment = new PostsBasedOnCategory();
bookFragment.setArguments(bundle);
AppCompatActivity activity = (AppCompatActivity) getContext();
activity.getSupportFragmentManager().beginTransaction().replace(R.id.flContainerFragment, bookFragment).addToBackStack(null).commit();
}
PostsBasedOnCategory.java
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_wordpress, container,false);
ButterKnife.bind(this,view);
setHasOptionsMenu(true);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
swipeRefreshLayout =(SwipeRefreshLayout) getActivity().findViewById(R.id.swipeRefreshLayout);
recycleViewWordPress =(RecyclerView) getActivity().findViewById(R.id.recycleViewWordPress);
pb = (ProgressBar) getActivity().findViewById(R.id.loadingPanel);
noFavtsTV = getActivity().findViewById(R.id.no_favt_text);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(false);
pb.setVisibility(View.VISIBLE);
recycleViewWordPress.setAdapter(mAdapter);
}
});
typeForPosts = new ArrayList<CategoriesModel>();
recycleViewWordPress.setHasFixedSize(true);
recycleViewWordPress.setLayoutManager(new LinearLayoutManager(getContext()));
recycleViewWordPress.setNestedScrollingEnabled(false);
mAdapter = new AdapterCategoryPosts(getContext(), typeForPosts, this);
recycleViewWordPress.setAdapter(mAdapter);
mAdapter.notifyDataSetChanged();
loadData();
}
public void loadData() {
Bundle bundel = this.getArguments();
long id = bundel.getLong("id");
String kategori = bundel.getString("kategori");
String title = bundel.getString("judul");
String excerpt = bundel.getString("excerpt");
String pict = bundel.getString("gambar");
String url = bundel.getString("url");
String konten = bundel.getString("konten");
CategoriesModel list = new CategoriesModel();
list.setId(id);
list.setCategory(kategori);
list.setJudul(title);
list.setExcerpt(excerpt);
list.setPostImg(pict);
list.setPostURL(url);
list.setContent(konten);
typeForPosts.add(list);
}
Logcat
2019-09-07 12:01:27.941 11246-11246/com.kursusarabic.arabicforfun D/postFrag: [{"id":12,"count":53,"description":"","link":"https:\/\/kisahmuslim.com\/category\/kisah-nyata\/biografi-ulama","name":"Biografi Ulama","slug":"biografi-ulama","taxonomy":"category","parent":29,"meta":[],"_links":{"self":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/12"}],"collection":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories"}],"about":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/taxonomies\/category"}],"up":[{"embeddable":true,"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/29"}],"wp:post_type":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/posts?categories=12"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}},{"id":26,"count":8,"description":"","link":"https:\/\/kisahmuslim.com\/category\/download","name":"Download","slug":"download","taxonomy":"category","parent":0,"meta":[],"_links":{"self":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/26"}],"collection":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories"}],"about":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/taxonomies\/category"}],"wp:post_type":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/posts?categories=26"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}},{"id":1812,"count":9,"description":"","link":"https:\/\/kisahmuslim.com\/category\/info","name":"Info","slug":"info","taxonomy":"category","parent":0,"meta":[],"_links":{"self":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/1812"}],"collection":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories"}],"about":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/taxonomies\/category"}],"wp:post_type":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/posts?categories=1812"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}},{"id":17,"count":3,"description":"","link":"https:\/\/kisahmuslim.com\/category\/kisah-nyata\/kisah-birrul-walidain","name":"Kisah Birrul Walidain","slug":"kisah-birrul-walidain","taxonomy":"category","parent":29,"meta":[],"_links":{"self":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/17"}],"collection":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories"}],"about":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/taxonomies\/category"}],"up":[{"embeddable":true,"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/29"}],"wp:post_type":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/posts?categories=17"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}},{"id":25,"count":31,"description":"","link":"https:\/\/kisahmuslim.com\/category\/kisah-nyata\/kisah-hidayah-islam","name":"Kisah Hidayah Islam","slug":"kisah-hidayah-islam","taxonomy":"category","parent":29,"meta":[],"_links":{"self":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/25"}],"collection":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories"}],"about":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/taxonomies\/category"}],"up":[{"embeddable":true,"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/29"}],"wp:post_type":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/posts?categories=25"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}},{"id":16,"count":49,"description":"","link":"https:\/\/kisahmuslim.com\/category\/kisah-nyata\/kisah-kaum-durhaka","name":"Kisah Kaum Durhaka","slug":"kisah-kaum-durhaka","taxonomy":"category","parent":29,"meta":[],"_links":{"self":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/16"}],"collection":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories"}],"about":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/taxonomies\/category"}],"up":[{"embeddable":true,"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/29"}],"wp:post_type":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/posts?categories=1
2019-09-07 12:01:27.942 11246-11246/com.kursusarabic.arabicforfun D/postFrag: Object at 0{"id":12,"count":53,"description":"","link":"https:\/\/kisahmuslim.com\/category\/kisah-nyata\/biografi-ulama","name":"Biografi Ulama","slug":"biografi-ulama","taxonomy":"category","parent":29,"meta":[],"_links":{"self":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/12"}],"collection":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories"}],"about":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/taxonomies\/category"}],"up":[{"embeddable":true,"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/categories\/29"}],"wp:post_type":[{"href":"https:\/\/kisahmuslim.com\/wp-json\/wp\/v2\/posts?categories=12"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}
2019-09-07 12:01:27.942 11246-11246/com.kursusarabic.arabicforfun D/postFrag: https://kisahmuslim.com/wp-json/wp/v2/posts?categories=12
You cannot call network requests in loop, Use async processing or
Retrofit & RxJava multiple requests complete
and after updating typeForPosts, there is no need to setAdapter on recyclerview just call adapter.notifyDataSetChanged()

Unable to access response data out of VolleyRequest, attempted callbacks

I have tried using callback similar to my fragments and other people suggestion on callbacks, However I've had no luck i could be doing the callbacks wrong. The Toast inside the onResponse method of JsonArrayRequest returns an array size of 2. But i get 0 on the toast outside of the request. consignment.class implements parcelable
public class BackgroundTask{
String json_url;
Gson gson;
Type listType;
ProgressDialog pDialog;
ArrayList<Consignment> arrayList = new ArrayList<>();
AppController appController;
ConsAdapter adapter;
Context context;
public BackgroundTask(Context context){
this.context = context;
listType = new TypeToken<List<Consignment>>(){}.getType();
appController = AppController.getInstance();
gson = new Gson();
}
public void getAllCons(final GetAllConsListener callBack) {
String tag_json_obj = "json_obj_req";
//showProgressDialog();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, json_url,null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
callBack.onSuccess(response.toString());
//hideProgressDialog();
Toast.makeText(context, "Consignments:"+arrayList.size(), Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(context, "Error...", Toast.LENGTH_SHORT).show();
error.printStackTrace();
//hideProgressDialog();
}
});
appController.addToRequestQueue(jsonArrayRequest);
}
Activity Class:
public class GetConsActivity extends AppCompatActivity {
RecyclerView recyclerView;
ConsAdapter adapter;
RecyclerView.LayoutManager layoutManager;
ArrayList<Consignment> arrayList;
TextView txtView;
BackgroundTask backgroundTask;
Type listType;
Gson gson;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_cons);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
gson = new Gson();
listType = new TypeToken<ArrayList<Consignment>>(){}.getType();
BackgroundTask backgroundTask = new BackgroundTask(GetConsActivity.this);
backgroundTask.getAllCons(new GetAllConsListener() {
#Override
public void onSuccess(String response) {
ArrayList<Consignment> list = parseResponse(response);
updateUI(list);
//Toast.makeText(GetConsActivity.this, "Consignments:"+arrayList.size(), Toast.LENGTH_LONG).show();
Log.d("ONSUCCESS", "ARRAYSIZE: "+arrayList.size());
}
});
}
public ArrayList<Consignment> parseResponse(String response){
ArrayList<Consignment> list = new ArrayList<>();
try {
JSONArray jsonArray = new JSONArray(response);
Log.d("PARSE", "parseResponse: "+jsonArray.length());
JSONObject jsonObject = jsonArray.getJSONObject(0);
for (int i = 0; i<jsonArray.length();i++){
Consignment con = null;
Log.d("PARSE", "parseID: "+jsonObject.getInt("conid"));
con.setConid(jsonObject.getInt("conid"));
Log.d("PARSE", "conID: "+con.getConid());
con.setDescription(jsonObject.getString("description"));
list.add(con);
}
Log.d("PARSED", "parsedResponse: "+list.size());
} catch (JSONException e) {
e.printStackTrace();
}
//arrayList =gson.fromJson(response,new TypeToken<ArrayList<Consignment>>(){}.getType());
//updateUI(arrayList);
return list;
}
public void updateUI(ArrayList<Consignment> consignments){
this.arrayList = consignments;
Log.d("UPDATE", "parseResponse: "+consignments.size());
if (adapter == null) {
adapter = new ConsAdapter(consignments,GetConsActivity.this);
recyclerView.setAdapter(adapter);
}else{
adapter.setConsignments(consignments);
adapter.notifyDataSetChanged();
}
}
Error:
D/mali_winsys: EGLint new_window_surface(egl_winsys_display*, void*, EGLSurface, EGLConfig, egl_winsys_surface**, egl_color_buffer_format*, EGLBoolean) returns 0x3000, [1440x2560]-format:1
E/RecyclerView: No adapter attached; skipping layout
I/qtaguid: Untagging socket 51
D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 84 - 0, 0) vi=Rect(0, 84 - 0, 0) or=1
E/RecyclerView: No adapter attached; skipping layout
D/PARSE: parseResponse: 4
D/PARSE: parseID: 123456789
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.angel.createcon, PID: 26952
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.angel.createcon.Consignment.setConid(int)' on a null object reference
at com.angel.createcon.GetConsActivity.parseResponse(GetConsActivity.java:80)
at com.angel.createcon.GetConsActivity$2.onSuccess(GetConsActivity.java:56)
at com.angel.createcon.BackgroundTask$2.onResponse(BackgroundTask.java:50)
at com.angel.createcon.BackgroundTask$2.onResponse(BackgroundTask.java:47)
at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7331)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
I/Process: Sending signal. PID: 26952 SIG: 9
Application terminated.
So I'll take a stab at this - having the activity implement the listener that way is a bit strange, though I don't think that's the issue. I also don't understand why you chose to save the list type to a variable - I've not seen anyone do that before.
However, getting to your question about the toast and why it's 0 - If you're talking about the toast that comes after the getAllCons call -it's because that code is executed before the callback code. completes.
Try something like this and see what it does.
public class BackgroundTask{
String json_url;
Gson gson;
Type listType;
Context context;
public BackgroundTask(Context context){
this.context = context;
listType = new TypeToken<List<Consignment>>(){}.getType();
appController = AppController.getInstance();
gson = new Gson();
}
public void getAllCons(final GetAllConsListener callBack) {
String tag_json_obj = "json_obj_req";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, json_url,null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
callBack.onSuccess(response.toString());
Toast.makeText(context, "Consignments:"+arrayList.size(), Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
appController.addToRequestQueue(jsonArrayRequest);
}
public class GetConsActivity extends AppCompatActivity {
RecyclerView recyclerView;
ConsAdapter adapter;
RecyclerView.LayoutManager layoutManager;
TextView txtView;
BackgroundTask backgroundTask;
Gson gson;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_cons);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
gson = new Gson();
BackgroundTask backgroundTask = new BackgroundTask(GetConsActivity.this);
backgroundTask.getAllCons(new GetAllConsListener() {
#Override
public void onSuccess(String response) {
List<Consignment> values = parseResponse(response);
updateUI(values);
}
});
//code may execute here but callback is not yet complete.
}
public List<Consignment> parseResponse(String response){
return gson.fromJson(response,listType);
}
private void updateUI(List<Consignment> consignments){
if(adapter == null){
adapter = new ConsAdapter(consignments)
recyclerView.setAdapter(adapter);
} else {
adapter.consignments = consignments;
adapter.notifyDataSetChanged();
}
}

Why do I get an IOException in sending an email with Gmail service?

In my android test application, after that i got the JSON file from the Google Developer Console, where i had set on the Gmail API, and that i have put it in the emulator, i get an IOException which says:
"com.google.api.client.googleapis.json.GoogleJsonResponseException:
403 Forbidden { "code" : 403, "errors" : [ {
"domain" : "usageLimits",
"message" : "Access Not Configured. Please use Google Developers Console to activate the API for your project.",
"reason" : "accessNotConfigured" } ], "message" : "Access Not Configured. Please use Google Developers Console to activate the API
for your project." }"
I think that I must use a GoogleClientSecrets object, but i haven't found its use.
Here the code:
public class MainActivity extends Activity
{
final String SCOPE = "oauth2:https://www.googleapis.com/auth/gmail.compose";
final String FILE_NAME = "TestEmail5.json";
private static final int REQUEST_RESOLVE_ERROR = 1001;
Button button;
OnClickListener sendListener = new OnClickListener()
{
#Override
public void onClick(View v)
{
new sendEmailTask().execute();
}
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button1);
button.setOnClickListener(sendListener);
}
public static MimeMessage createEmail(String to, String from, String subject, String bodyText) throws MessagingException
{
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
MimeMessage email = new MimeMessage(session);
InternetAddress tAddress = new InternetAddress(to);
InternetAddress fAddress = new InternetAddress(from);
email.setFrom(new InternetAddress(from));
email.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
email.setSubject(subject);
email.setText(bodyText);
return email;
}
public static void sendMessage(Gmail service, String userId, MimeMessage email) throws MessagingException, IOException
{
Message message = createMessageWithEmail(email);
message = service.users().messages().send(userId, message).execute();
System.out.println("Message id: " + message.getId());
System.out.println(message.toPrettyString());
}
public static Message createMessageWithEmail(MimeMessage email) throws MessagingException, IOException
{
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
email.writeTo(bytes);
String encodedEmail = Base64.encodeBase64URLSafeString(bytes.toByteArray());
Message message = new Message();
message.setRaw(encodedEmail);
return message;
}
public class sendEmailTask extends AsyncTask
{
#Override
protected Object doInBackground(Object... params)
{
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
String token = "";
AccountManager accountManager = AccountManager.get(MainActivity.this);
Account account[] = accountManager.getAccountsByType("com.google");
String accountName = account[0].name;
try
{
//GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(jsonFactory, new java.io.FileReader(Environment.getExternalStorageDirectory().getAbsolutePath() + "//" + "JSON/" + FILE_NAME));
token = GoogleAuthUtil.getToken(MainActivity.this, accountName, SCOPE);
GoogleCredential credential = new GoogleCredential().setAccessToken(token);
Gmail service = new Gmail.Builder(httpTransport, jsonFactory, credential).setApplicationName("TestEmail5").build();
MimeMessage mm = createEmail("myemail", "myemail", "soggetto", "oggetto");
sendMessage(service, "myemail", mm);
}
catch (UserRecoverableAuthException e)
{
startActivityForResult(e.getIntent(), REQUEST_RESOLVE_ERROR);
}
catch (IOException e)
{
e.printStackTrace();
}
catch (GoogleAuthException e)
{
e.printStackTrace();
}
catch (MessagingException e)
{
e.printStackTrace();
}
return null;
}
};
}
You need to login to http://console.developers.google.com/ and create a project and activate the "Gmail" API for it.
Documented more at:
https://developers.google.com/gmail/api/quickstart/quickstart-java#step_1_enable_the_gmail_api

AsyncTask HttpConnection in Android

I want to create httpconnection using asyntask.three parameters are posted to the server
username,password and a search item.the search is provided by the user in an EditText such so that when the user clicks a button,the search item is sent to the server.I want to execute the doInbackground() method in the OnclickListener and display the response from the server on listviews.This is the AsyncTask Class
public class PostToServer extends AsyncTask<String, Void, String> {
#Override
protected void onPostExecute(String result) {
}
#Override
protected String doInBackground(String... arg0) {
try {
HttpClient client = new DefaultHttpClient();
String postURL = "url";
String username ="username";
String password = "password";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user", username));
params.add(new BasicNameValuePair("pass", password));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
if (resEntity != null) {
Log.i("RESPONSE",EntityUtils.toString(resEntity));
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
This the class where the click event is called
public class StartPost extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_page);
}
Button Submit = (Button) findViewById(R.id.btn_search);
EditText textvalue = (EditText)findViewById(R.id.searcheditText);
String value = textvalue.getText().toString();
PostToServer post = new PostToServer();
CheckInternetConnection check = new CheckInternetConnection(null);
private OnClickListener click = new OnClickListener() {
#Override
public void onClick(final View v) {
switch(v.getId()){
case R.id.btn_search:
post.execute();
break;
}
}
};
}
Questions
1.What am I doing wrong because it seems the post is not working and How can I display the server results from the onPostExecute()?
Thank You.
Create a onPostExecute method to display the results on your textview.
protected onPostExecute (String result){
TextView tv = (TextView) findViewById(R.id.textview1);
if(result != null){
tv.setText(result);
}
}

java.lang.NullPointerException in textview inside asyncTask

If I use the following code, I will have no error, but there will be a freeze time.
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.profilepic);
initialize();
Bundle bundle = getIntent().getExtras();
email = bundle.getString("Email");
ArrayList<NameValuePair> postParameters;
String response = null;
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("emaillog", email));
try {
response = CustomHttpClient.executeHttpPost("http://whatstherex.info/checkU.php", postParameters);
res = response.toString();
res = res.replaceAll("null", "");
username = res.toString();
tvProfilePic.setText("Hi " + username + ", you are encourage to add a profile picture.");
}catch(Exception e){
res = e.toString();
tvProfilePic.setText(res);
}
}
But if I use this code with asyncTask and progressDialog like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.profilepic);
initialize();
getUsername();
}
private AsyncTask<String, Void, String> task;
public void getUsername(){
Bundle bundle = getIntent().getExtras();
email = bundle.getString("Email");
task = new AsyncTask<String, Void, String>() {
ProgressDialog dialog;
ArrayList<NameValuePair> postParameters;
String response = null;
#Override
protected void onPreExecute() {
//
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("emaillog", email));
dialog = new ProgressDialog(Profilepic.this, ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Loading Data...");
dialog.show();
}
#Override
protected String doInBackground(String... params) {
//
try {
response = CustomHttpClient.executeHttpPost("http://whatstherex.info/checkU.php", postParameters);
res = response.toString();
res = res.replaceAll("null", "");
username = res.toString();
return username;
}catch(Exception e){
res = e.toString();
return res;
}
}
#Override
protected void onPostExecute(String result) {
if(result.length()< 25){
username = result;
tvProfilePic.setText("Hi " + result + ", you are encourage to add a profile picture.");
dialog.dismiss();
}else{
tvProfilePic.setText(result);
dialog.dismiss();
}
}
};
task.execute();
}
I get java.lang.NullPointerException in the textview.
What's the problem? Can anyone help me how to resolve this issue with NullPointerException appearing?
I see that you use tvProfilePic but I don't see where you define it.
In case you are not defining it, it should be done in a similar way as
tvProfilePic = findViewById(R.id.profile_pic)
Are you doing this?
Note that 'profile_pic' is the name in the layout XML document.
You are using tvProfilePic as a textview but i can't see where you defined it.
if you are not defining it then define it using something like
tvProfilePic = findViewById(R.id.profile_pic)
You are getting nullpointerexception because your tvProfilePic is null

Resources