onPostExecute() doesn't start - java

I have a problem with some information downloaded from a DDBB. I recieve all the information, but I can't store it on my arrays because the onPostExecute() method doesn't starts. I put my code:
RequestRocodromo.java, is the class for making the request and recieve the information, on "results" variable I have all the information, but I can't storage it on the arrays of onPostExecute():
#Override
protected JSONObject doInBackground(String... params)
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(_url);
String results = "NO OK";
try
{
// Add your data
/*List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("mac", _mac ));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));*/
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
response.getAllHeaders();
response.getEntity();
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
results = EntityUtils.toString(response.getEntity());
}
broadcastIntent = new Intent();
broadcastIntent.putExtra("correcto", results);
broadcastIntent.setAction(ACTION_REQUEST_ROCODROMO);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
_ctx.sendBroadcast(broadcastIntent);
}
catch (Exception ex)
{
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject jsonResponse)
{
super.onPostExecute(jsonResponse);
List<String> values = new ArrayList<String>();
ArrayList<String> rocodromoId = new ArrayList<String>();
ArrayList<String> rocodromoArray = new ArrayList<String>();
ArrayList<String> ciudadArray = new ArrayList<String>();
ArrayList<String> comentarioArray = new ArrayList<String>();
//Procesamos los resultados
try
{
if(jsonResponse != null)
{
JSONArray jsonMainNode =jsonResponse.optJSONArray("edificios");
int lengthJsonArr =jsonMainNode.length();
for(int i=0; i<lengthJsonArr; i++)
{
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
rocodromoId.add(jsonChildNode.optString("id"));
rocodromoArray.add(jsonChildNode.optString("nombre"));
ciudadArray.add(jsonChildNode.optString("ciudad"));
comentarioArray.add(jsonChildNode.optString("comentario"));
values.add(jsonChildNode.optString("nombre"));
}
}
String result[] = values.toArray(new String[values.size()]);
broadcastIntent = new Intent();
broadcastIntent.putExtra("edificios", result);
broadcastIntent.putStringArrayListExtra("id_rocodromo", rocodromoId);
broadcastIntent.putStringArrayListExtra("rocodromoArray", rocodromoArray);
broadcastIntent.putStringArrayListExtra("ciudadArray", ciudadArray);
broadcastIntent.putStringArrayListExtra("comentarioArray", comentarioArray);
broadcastIntent.setAction(ACTION_REQUEST_ROCODROMO);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
_ctx.sendBroadcast(broadcastIntent);
}
catch (Exception e)
{
String result = "null";
broadcastIntent = new Intent();
broadcastIntent.putExtra("edificios", result);
broadcastIntent.putStringArrayListExtra("id_rocodromo", rocodromoId);
broadcastIntent.putStringArrayListExtra("rocodromoArray", rocodromoArray);
broadcastIntent.putStringArrayListExtra("ciudadArray", ciudadArray);
broadcastIntent.putStringArrayListExtra("comentarioArray", comentarioArray);
broadcastIntent.setAction(ACTION_REQUEST_ROCODROMO);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
_ctx.sendBroadcast(broadcastIntent);
}
}
Rocodromo.java, here is where I start the execute method:
RequestRocodromo re = new RequestRocodromo(ctx, finalURL + "request=1");
re.execute("");
Rocodromo.java, here is my broadcast, when I try to obtain the arraylist information I recieve a nullException, because my arraylist are null because it never starts the onPostExecute() method.
public class ReceptorBroadcast extends BroadcastReceiver
{
#Override
public void onReceive(Context arg0, Intent intent)
{
if(RequestRocodromo.ACTION_REQUEST_ROCODROMO.equals(intent.getAction()))
{
idRocodromo = intent.getStringArrayListExtra("id_rocodromo");
Toast.makeText(getApplicationContext(), idRocodromo.get(0).toString(), Toast.LENGTH_LONG).show();
rocodromo = intent.getStringArrayListExtra("rocodromoArray");
Toast.makeText(getApplicationContext(), rocodromo.get(0).toString(), Toast.LENGTH_LONG).show();
ciudad = intent.getStringArrayListExtra("ciudadArray");
Toast.makeText(getApplicationContext(), ciudad.get(0).toString(), Toast.LENGTH_LONG).show();
comentario = intent.getStringArrayListExtra("comentarioArray");
Toast.makeText(getApplicationContext(), comentario.get(0).toString(), Toast.LENGTH_LONG).show();
}
}
}
Can someone help my with that? Thanks! :)

Change on doInBackGround return null to:
try {
return new JSONObject(reusults);
} catch (Throwable t) {
return null;
}

Change you broadcast receiver call in your doInBackground().. as
runOnUiThread(new Runnable() {
#Override
public void run() {
broadcastIntent = new Intent();
broadcastIntent.putExtra("correcto", results);
broadcastIntent.setAction(ACTION_REQUEST_ROCODROMO);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
_ctx.sendBroadcast(broadcastIntent);
}
});
and check null result in onPostExecute as..
if(null!=jsonResponse) // avoids null pointer;

Related

How to get the JSON error response and toast it?

Here's my code for when i trying to register user and need a toast which is response from server regarding user already exist. i can post successfully to server using json but if there's response i have to idea how to catch it the image shows example when using postman.
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener{
private EditText signupInputName, signupInputEmail, signupInputPassword, retypeInputPassword;
private Button btnSignUp;
private Button btnLinkLogin;
private String message = "";
private int code = 0;
Person person;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
signupInputName = (EditText) findViewById(R.id.signup_input_name);
signupInputEmail = (EditText) findViewById(R.id.signup_input_email);
signupInputPassword = (EditText) findViewById(R.id.signup_input_password);
retypeInputPassword = (EditText) findViewById(R.id.signup_retype_password);
btnSignUp = (Button) findViewById(R.id.btn_signup);
btnLinkLogin = (Button) findViewById(R.id.btn_link_login);
btnSignUp.setOnClickListener(this);
btnLinkLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),LoginActivity.class);
startActivity(i);
}
});
}
public String POST(String url, Person person)
{
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httppost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("user_name", person.getUsername());
jsonObject.accumulate("email", person.getEmail());
jsonObject.accumulate("password", person.getPassword());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httppost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httppost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Error! email exist";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
#Override
public void onClick(View view) {
if(validate() == 1)
{
Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show();
}
else if (validate() == 2)
{
Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show();
}
else if (validate() == 3)
{
Toast.makeText(getBaseContext(), message.toString(), Toast.LENGTH_SHORT).show();
}
else if (validate() == 4)
{
//Toast.makeText(getBaseContext(), "Success", Toast.LENGTH_SHORT).show();
new HttpAsyncTask().execute("http://ip-addressses/api/register");
}
}
private class HttpAsyncTask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urls) {
person = new Person();
person.setUsername(signupInputName.getText().toString());
person.setEmail(signupInputEmail.getText().toString());
person.setPassword(signupInputPassword.getText().toString());
return POST(urls[0],person);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
JSONObject jObject;
try {
jObject = new JSONObject(result);
if (jObject.has("error")) {
String aJsonString = jObject.getString("error");
Toast.makeText(getBaseContext(), aJsonString, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Login Successful", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
private int validate() {
if(signupInputName.getText().toString().trim().equals("") || signupInputEmail.getText().toString().trim().equals("") || signupInputPassword.getText().toString().trim().equals("") || retypeInputPassword.getText().toString().trim().equals(""))
{
code = 1;
message = "Complete the form!";
}
else if (!(signupInputPassword.getText().toString().equals(retypeInputPassword.getText().toString())))
{
code = 2;
message = "Re-check password";
}
else if (!isValidEmail(signupInputEmail.getText().toString()) ) {
code = 3;
message = "Invalid email";
}
else
code = 4;
return code;
}
public final static boolean isValidEmail(String target)
{
if (target == null) {
return false;
} else {
Matcher match = Patterns.EMAIL_ADDRESS.matcher(target);
return match.matches();
}
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
}
Postman response when email exist
Just change this code:
jObject = new JSONObject(result);
if (jObject.has("error"))
{
String aJsonString = jObject.getString("error");
Toast.makeText(getBaseContext(), aJsonString, Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Login Successful", Toast.LENGTH_SHORT).show();
}
}
catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
Toast.makeText(getBaseContext(),result+"" , Toast.LENGTH_SHORT).show();
}
So by this code, if your response is not JSON it will throw exception in catch. And here you can show toast.

Fetch sms From phone and upload on server

Here i am fetch sms from phone and upload 10 sms on server all code working fine but instead of 10 sms upload to server only Specific one sms uploaded 10 time to server, pls tell me what i am missing in my code?
here is my message_class.Java code.
public class message_class extends Activity{
int j = 0;
Button btninbox;
ListView lstView;
SimpleCursorAdapter adapter;
ArrayList<Message_Item> msg_list;
String Str_Msg, Str_Phone,dated;
Msg_adapter msg_adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.msginbox_layout);
msg_list = new ArrayList<Message_Item>();
btninbox = (Button) findViewById(R.id.btn_inbox);
btninbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(message_class.this, Msg_Recive.class);
startActivity(intent);
}
});
lstView = (ListView) findViewById(R.id.lv_msg);
fetchInbox();
final int arraysize = msg_list.size();
for (int j=0; j<10;j++){
Str_Msg = msg_list.get(j).getStrMsg().toString();
Str_Phone = msg_list.get(j).getStrNumber().toString();
Toast.makeText(message_class.this, Str_Phone+" "+Str_Msg, Toast.LENGTH_LONG).show();
new HttpAsyncTask()
.execute("http://demo.glowsosl.com/synchs_dsda_app/insert_details_msg.php");
msg_adapter.notifyDataSetChanged();
}
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
Contacts person = new Contacts();
person.setPhone(Str_Phone);
person.setName(Str_Msg);
return POST(urls[0], person);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), result + "Data Sent!",
Toast.LENGTH_LONG).show();
}
}
private static String convertInputStreamToString(InputStream inputStream)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
public static String POST(String url, Contacts person) {
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("contact_no", person.getPhone());
jsonObject.accumulate("sim_num", "Unknown");
jsonObject.accumulate("msg", person.getName());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the
// content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result + "," + person.getName() + ","
+ person.getPhone();
}
ArrayList<String> jsonStringToArray(String jsonString) throws JSONException {
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray jsonArray = new JSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++) {
stringArray.add(jsonArray.getString(i));
}
return stringArray;
}
public void fetchInbox() {
// ArrayList sms = new ArrayList();
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor cursor = getContentResolver().query(uriSms,
new String[] { "_id", "address", "date", "body" }, null, null,
null);
//for (int i =0; i<((JSONArray) cursor).length();i++){
//Toast.makeText(getApplicationContext(), "work", Toast.LENGTH_SHORT).show();
//}
cursor.moveToFirst();
while (cursor.moveToNext()) {
String address = cursor.getString(1);
String date = cursor.getString(2);
String body = cursor.getString(3);
// Toast.makeText(getApplicationContext(), cursor.getString(2), Toast.LENGTH_SHORT).show();
msg_list.add(new Message_Item(address, body,date));
}
msg_adapter = new Msg_adapter(msg_list, message_class.this);
lstView.setAdapter(msg_adapter);
}
Instead of applying for loop out side async task use it in doInBackground method.
Your doInBackground method will look like follows.
#Override
protected String doInBackground(String... urls) {
String result="";
for(int i = 0; i < msg_list.size(); i++){
Str_Msg = msg_list.get(i).getStrMsg().toString();
Str_Phone = msg_list.get(i).getStrNumber().toString();
Contacts person = new Contacts();
person.setPhone(Str_Phone);
person.setName(Str_Msg);
result= result + POST(urls[0], person);
}
return result;
}
And call this async task only once.
Enjoy!!

Android Studio app show the error message to user

guys I have a problem with implement error handling in my application.
I want to display the error message to the user of my application when the response code from rest is not 200. In other words: If the connection is wrong, I want to display the message, that the user have to check his internet connection and try again. If everything is fine I want to do everything as usual so load the content.
I write something like this:
Toast errorToast = Toast.makeText(NewsActivity.this, "Error, pls chech your internet connection and try again!", Toast.LENGTH_SHORT);
errorToast.show();
and this:
if(response.getStatusLine().getStatusCode() == 200){}
But i don't know If this is good code and where should I insert it. I will be very grateful for your help and advice.
This is this code:
public class NewsActivity extends Activity {
private static final String URL = "http://10.0.2.2:8083/rest/aktualnosci";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
new FetchItems().execute();
}
private class FetchItems extends AsyncTask<String, Void, JSONArray> {
protected JSONArray doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(URL);
httpget.setHeader("Content-type", "application/json");
JSONArray json = new JSONArray();
try {
HttpResponse response = httpclient.execute(httpget);
json = new JSONArray(EntityUtils.toString(response.getEntity()));
return json;
}
} catch (Exception e) {
Log.v("Błędne wczytanie", e.getMessage());
}
return json;
}
protected void onPostExecute(JSONArray result) {
ListView lst = (ListView) findViewById(R.id.aktualnosci_list);
ArrayList<String> listItems = new ArrayList<String>();
String contentToEdit;
String titleContainer;
TextView newsHeaderTextView = null;
for (int i = 0; i < result.length(); i++) {
try {
titleContainer = result.getJSONObject(i).getString("title").toString();
listItems.add(titleContainer);
contentToEdit=result.getJSONObject(i).getString("body").toString();
contentToEdit= Html.fromHtml(contentToEdit).toString();
listItems.add(contentToEdit);
} catch (Exception e) {
Log.v("Błędne wczytanie1", e.getMessage());
}
}
ArrayAdapter ad = new ArrayAdapter(NewsActivity.this, android.R.layout.simple_list_item_1, listItems);
lst.setAdapter(ad);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
You can add this in doInBackground method.
runOnUiThread(new Runnable() {
public void run() {
if (response.getStatusLine().getStatusCode() != 200) {
Toast errorToast = Toast.makeText(NewsActivity.this, "Error, pls chech your internet connection and try again!", Toast.LENGTH_SHORT);
errorToast.show();
}
}
});
/*
I thought Your Code Working Fine Made Some Changes As Per Need
*/
public class NewsActivity extends Activity {
private static final String URL = "http://10.0.2.2:8083/rest/aktualnosci";
String jsonArrayString = "";
String message = "Error, pls check your internet connection and try again!";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
new FetchItems().execute(this);
}
private class FetchItems extends AsyncTask<Context,Void,String>{
Context temp;
#Override
protected String doInBackground(Context... params) {
temp = params[0];
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(URL);
httpget.setHeader("Content-type", "application/json");
JSONArray json = new JSONArray();
try {
HttpResponse response = httpclient.execute(httpget);
if(response.getStatusLine().getStatusCode() == 200) {
json = new JSONArray(EntityUtils.toString(response.getEntity()));
jsonArrayString += json.toString();
return jsonArrayString;
}
}
catch (Exception e) {
Log.v("Błędne wczytanie", e.getMessage());
}
return message;
}
#Override
protected void onPostExecute(String s) {
ListView lst = (ListView) findViewById(R.id.aktualnosci_list);
ArrayList<String> listItems = new ArrayList<String>();
String contentToEdit;
String titleContainer;
TextView newsHeaderTextView = null;
if(!message.equals(s))
{
JSONArray result = null;
try {
result = new JSONArray(s);
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < result.length(); i++) {
try {
titleContainer = result.getJSONObject(i).getString("title").toString();
listItems.add(titleContainer);
contentToEdit=result.getJSONObject(i).getString("body").toString();
contentToEdit= Html.fromHtml(contentToEdit).toString();
listItems.add(contentToEdit);
} catch (Exception e) {
Log.v("Błędne wczytanie1", e.getMessage());
}
}
ArrayAdapter ad = new ArrayAdapter(NewsActivity.this, android.R.layout.simple_list_item_1, listItems);
lst.setAdapter(ad);
}
else
{
Toast.makeText(temp,message,Toast.LENGTH_LONG).show();
}
}
}
}

java.lang.String cannot be converted to JSONObject

I'm trying to parse below JSON which is received from server
{"status":1,"data":{"msg":"Invertory Added","inventory_id":2001}}
Using Below
try
{
jObj = new JSONObject(json);
final Integer status = jObj.getInt("status");
if(status == 1) {
msg="Inventory Created Successfully";
} else {
msg = jObj.getString("data");
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Info")
.setMessage(msg)
.setCancelable(false)
.setIcon(R.drawable.ic_launcher)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
if(status==1)
{
displayView(6);
}
}
});
AlertDialog alert = builder.create();
alert.show();
} catch (JSONException e) {
Log.e("msgtest", "unexpected JSON exception", e);
// Do something to recover ... or kill the app.
}
Log says
E/msgtest﹕ unexpected JSON exception
org.json.JSONException: Value org.apache.http.conn.BasicManagedEntity#41f14cd0 of type java.lang.String cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:111)
at org.json.JSONObject.<init>(JSONObject.java:158)
at org.json.JSONObject.<init>(JSONObject.java:171)
at info.androidhive.wolf.NewInventoryFragment$submitAction.onPostExecute(NewInventoryFragment.java:575)
at info.androidhive.wolf.NewInventoryFragment$submitAction.onPostExecute(NewInventoryFragment.java:388)
at line #575 jObj = new JSONObject(json);
AsyncTask
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
File file1 = new File(selectedPath1);
File file2 = new File(selectedPath2);
File file3 = new File(selectedPath3);
File file4 = new File(selectedPath4);
File file5 = new File(selectedPath5);
String urlString="http://url/index.php";
List<NameValuePair> params = new ArrayList<NameValuePair>();
try
{
FileBody bin2 = new FileBody(file2);
FileBody bin3 = new FileBody(file3);
FileBody bin4 = new FileBody(file4);
FileBody bin5 = new FileBody(file5);
params.add(new BasicNameValuePair("section","inventory"));
params.add(new BasicNameValuePair("action","new"));
params.add(new BasicNameValuePair("apron_id",stock_number_ele.getText().toString()));
params.add(new BasicNameValuePair("nickname",nick_name_ele.getText().toString()));
params.add(new BasicNameValuePair("location",location));
params.add(new BasicNameValuePair("manufacture",manufacture));
params.add(new BasicNameValuePair("core_material",core_material_ele.getText().toString()));
params.add(new BasicNameValuePair("color",color_ele.getText().toString()));
params.add(new BasicNameValuePair("Date_purchase",dop_ele.getText().toString()));
params.add(new BasicNameValuePair("UID_no",gtin_uid_ele.getText().toString()));
params.add(new BasicNameValuePair("serial",serial_ele.getText().toString()));
params.add(new BasicNameValuePair("Batch",batch_lot_ele.getText().toString()));
params.add(new BasicNameValuePair("Expiration",ed_ele.getText().toString()));
params.add(new BasicNameValuePair("garment_type",description_ele.getText().toString()));
params.add(new BasicNameValuePair("QTY",county_ele.getText().toString()));
params.add(new BasicNameValuePair("user_id",SignInActivity.user_id));*/
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
FileBody bin1 = new FileBody(file1);
FileBody bin2 = new FileBody(file2);
FileBody bin3 = new FileBody(file3);
FileBody bin4 = new FileBody(file4);
FileBody bin5 = new FileBody(file5);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("section", new StringBody("inventory"));
reqEntity.addPart("action", new StringBody("new"));
reqEntity.addPart("apron_id", new StringBody(stock_number_ele.getText().toString()));
reqEntity.addPart("nickname", new StringBody(nick_name_ele.getText().toString()));
reqEntity.addPart("location", new StringBody(location+""));
reqEntity.addPart("manufacture", new StringBody(manufacture+""));
reqEntity.addPart("core_material", new StringBody(core_material_ele.getText().toString()));
reqEntity.addPart("color", new StringBody(color_ele.getText().toString()));
reqEntity.addPart("Date_purchase", new StringBody(dop_ele.getText().toString()));
reqEntity.addPart("UID_no", new StringBody(gtin_uid_ele.getText().toString()));
reqEntity.addPart("serial", new StringBody(serial_ele.getText().toString()));
reqEntity.addPart("Batch", new StringBody(batch_lot_ele.getText().toString()));
reqEntity.addPart("Expiration", new StringBody(ed_ele.getText().toString()));
reqEntity.addPart("garment_type", new StringBody(description_ele.getText().toString()));
reqEntity.addPart("QTY", new StringBody(county_ele.getText().toString()));
reqEntity.addPart("user_id", new StringBody(SignInActivity.user_id));
if(selectedPath1!="NONE")
reqEntity.addPart("image1", bin1);
if(selectedPath2!="NONE") {
Log.d("Image2","Image2");
reqEntity.addPart("image2", bin2);
}
if(selectedPath3!="NONE") {
Log.d("Image3","Image2");
reqEntity.addPart("image3", bin3);
}
if(selectedPath4!="NONE") {
Log.d("Image4","Image2");
reqEntity.addPart("image4", bin4);
}
if(selectedPath5!="NONE") {
Log.d("Image5","Image2");
reqEntity.addPart("image5", bin5);
}
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
final String response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE",response_str);
}
}
catch (Exception ex)
{
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
return resEntity.toString();
}
#SuppressWarnings("deprecation")
//#Override
protected void onPostExecute(String json) {
String msg="";
JSONArray jArray=null;
if (pDialog.isShowing()) {
pDialog.dismiss();
}
try
{
jObj = new JSONObject(json);
final Integer status = jObj.getInt("status");
msg = jObj.getString("data"); // get the name from data.
if (status == 1) {
msg="Inventory Created Successfully";
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Info")
.setMessage(msg)
.setCancelable(false)
.setIcon(R.drawable.ic_launcher)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
if(status==1)
{
displayView(6);
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
catch (JSONException e)
{
Log.e("msgtest", "unexpected JSON exception", e);
// Do something to recover ... or kill the app.
}
}
Please suggest your views . Thanks in advance.
your are correctly using EntityUtils.toString to read the content of the entity and as a String, but you are returning the wrong object in doInBackground. Instead of returning resEntity.toString();, you have to return response_str.
I think I know why this code is failing.
in your code you have :
try
{
jObj = new JSONObject(json);
final Integer status = jObj.getInt("status");
if(status == 1)
{
msg = "Inventory Created Successfully";
}
else
{
msg = jObj.getString("data");
}
...
}
catch (JSONException e)
{
Log.e("msgtest", "unexpected JSON exception", e);
// Do something to recover ... or kill the app.
}
You said that you were receiving JSON messages like this (I added the types of the fields):
// "Main" Object
{
"status": 1, // Integer
"data": // Object
{
"msg" : "Invertory Added", // String
"inventory_id" : 2001 // Integer
}
}
So in your code when you try this msg = jObj.getString("data"); you ask a String BUT in your JSON message "data" is of the type Object which is why you get this Error.
So instead you should do this :
try
{
jObj = new JSONObject(json);
final Integer status = jObj.getInt("status");
if(status == 1)
{
msg = "Inventory Created Successfully";
}
else
{
// Here is the change
// you should also change the type of msg to JSONObject
// and probably the name of the variable for a better understanding
msg = jObj.getObject("data");
}
// And of course handle this object accordingly
// Example : String message = msg.getString("msg");
...
}
catch (JSONException e)
{
Log.e("msgtest", "unexpected JSON exception", e);
// Do something to recover ... or kill the app.
}
If I am guessing right you wanted to retrieve the "msg" field inside the "data" Object. You can simply get it like so :
String message = jObj.getObject("data").getString("msg");
Hope this helps,
Cheers.

Get value from Async task in Activity

I have a class as shown below. It is in a .java file called NQRequestHandler.java and I want to call this from an Activity.java. But I'm having problems with the AsyncTask method. When I run it in the Activity.java file it returns a null
value when I try to log the value of Globals.PUBLIC_KEY from the Activity.
Log.v("RESULT", "Public KEY JSON from OnStart" + Globals.PUBLIC_KEY);
public class NQRequestHandler {
private static NQRequestHandler instance;
public static final String TAG = NQRequestHandler.class.getSimpleName();
private Context mContext;
public NQRequestHandler(Context context) {
mContext = context;
}
public static synchronized NQRequestHandler getInstance(Context context) {
if (instance == null)
instance = new NQRequestHandler(context);
return instance;
}
public class requestHandler extends AsyncTask<String, Void, JSONArray> {
RequestListener requestListener;
public JSONArray requestResult;
public requestHandler() {
}
public void setRequestListener(RequestListener requestListener) {
this.requestListener = requestListener;
}
#Override
protected JSONArray doInBackground(String... params) {
try {
String url = "http://www.someurl.com";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> urlParameters = requestHandlerHelper(params);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(urlParameters);
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8"));
post.setEntity(entity);
HttpResponse response = client.execute(post);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
Reader reader = new InputStreamReader(response.getEntity().getContent());
int contentLength = (int) response.getEntity().getContentLength();
Log.v(TAG, "Content Length DATA" + contentLength);
char[] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
JSONArray jsonResponse = new JSONArray(responseData);
return jsonResponse;
} catch (ClientProtocolException e) {
Log.i(TAG, "ClientProtocolException: ", e);
} catch (UnsupportedEncodingException e) {
Log.i(TAG, "UnsupportedEncodingException: ", e);
} catch (IOException e) {
Log.i(TAG, "IOException: ", e);
} catch (JSONException e) {
Log.i(TAG, "JSONException: ", e);
}
return null;
}
#Override
protected void onPostExecute(JSONArray results) {
if (results != null) {
requestListener.onRequestSuccess(results);
} else {
requestListener.onRequestFailed();
}
}
}
public interface RequestListener {
JSONArray onRequestSuccess(JSONArray data);
void onRequestFailed();
}
public void NQRequest(String... params) {
if (isNetworkAvailable()) {
requestHandler handler = new requestHandler();
RequestListener listener = new RequestListener() {
#SuppressWarnings("unchecked")
#Override
public JSONArray onRequestSuccess(JSONArray data) {
//TODO: Switch set data here
Log.v(TAG, "JSON FROM NQRequest" + data);
Globals.PUBLIC_KEY = String.valueOf(data);
return data;
}
#Override
public void onRequestFailed() {
Toast.makeText(mContext, "Network is unavailable. Request failed", Toast.LENGTH_LONG).show();
}
};
handler.setRequestListener(listener);
handler.execute(params);
} else {
Toast.makeText(mContext, "Network is unavailable", Toast.LENGTH_LONG).show();
}
}
private static List<NameValuePair> requestHandlerHelper(String... params) {
//Declare URL Parameter values
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
String[] requestActionArray = Globals.REQUEST_ACTION_ID;
int actionSwitch = -1;
String[] requestActionHeaders = null;
//Find URL Parameter Action Switch
for (int i = 0; i < requestActionArray.length; i++) {
if (requestActionArray[i].equalsIgnoreCase(params[params.length - 1])) {
actionSwitch = i;
}
}
//Set Action Switch ID Parameters
requestActionHeaders = NQActionHeader(actionSwitch);
//Set URL Parameters
for (int i = 0; i < requestActionHeaders.length; i++) {
urlParameters.add(new BasicNameValuePair(requestActionHeaders[i], params[i]));
}
return urlParameters;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager =
(ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected() ? true : false;
}
private static String[] NQActionHeader(int actionSwitch) {
/* some code goes here */
}
}
In the Activity class looks like this:
public class Application extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
String message = "Hello World from Android";
Context mContext = getBaseContext();
NQRequestHandler.requestHandler handler = new NQRequestHandler.requestHandler();
NQRequestHandler requestHandler = NQRequestHandler.getInstance(mContext);
requestHandler.NQRequest(message, "sendPublicKey");
Log.v("RESULT", "Public KEY JSON from OnStart" + Globals.PUBLIC_KEY);
//Start Activity
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The call to NQRequest in the Activity initiates the call to AsyncTask in the Activity. Any help with this? How do I implement a callback in the Activity.java to get method from OnRequestSuccess(); in the NQRequest()? Note: I'm trying to call the method in Activity.java in other multiple Activity.java files
i modified the structure for your reference.
Modified of requestHandler :-
//**** e.g.
class requestHandler extends AsyncTask<Object, Void, JSONArray> {
// define a caller
String requester;
Application caller;
YourEachActivityClass1 caller1;
//create a Constructor for caller;
public requestHandler (Application caller) {
// TODO Auto-generated constructor stub
this.caller = caller;
}
public requestHandler (YourEachActivityClass1 caller1) {
// TODO Auto-generated constructor stub
this.caller1 = caller1;
}
///&& method doInBackground
#Override
protected JSONArray doInBackground(Object... params) {
.....
//your process is here
//custom your returning jsonarray
try {
Context context = (Context) params[0];
Log.i(TAG, "context :"+context.getClass().getSimpleName());
requester = (Integer) params[1];
String message = (String) params[2];
String public= (String) params[3]
String url = "http://www.someurl.com";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> urlParameters = requestHandlerHelper(params);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(urlParameters);
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8"));
post.setEntity(entity);
HttpResponse response = client.execute(post);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
Reader reader = new InputStreamReader(response.getEntity().getContent());
int contentLength = (int) response.getEntity().getContentLength();
Log.v(TAG, "Content Length DATA" + contentLength);
char[] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
JSONArray jsonResponse = new JSONArray(responseData);
Globals.PUBLIC_KEY = String.valueOf(jsonResponse);
return jsonResponse;
} catch (ClientProtocolException e) {
Log.i(TAG, "ClientProtocolException: ", e);
} catch (UnsupportedEncodingException e) {
Log.i(TAG, "UnsupportedEncodingException: ", e);
} catch (IOException e) {
Log.i(TAG, "IOException: ", e);
} catch (JSONException e) {
Log.i(TAG, "JSONException: ", e);
}
return null;
}
////&& return JSONArray back to ur activity class here by pass in caller
protected void onPostExecute(JSONArray jsonarray) {
if(requester.equals("IM_Application"))
caller.onBackgroundTaskCompleted(jsonarray);
else if(requester.equals("IM_ACTIVITY_1"))
caller1.onBackgroundTaskCompleted(jsonarray);
}
}
Application.class get ur json object:-
public class Application extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
String message = "Hello World from Android";
new requestHandler(this).execute(getActivity(), "IM_Application", message, "sendPublicKey");
} catch (Exception e) {
e.printStackTrace();
}
}
//your returning result
public void onBackgroundTaskCompleted(JSONArray jsonarray) {
Log.i("TAG", jsonarray:"+jsonarray);
if(jsonarray!=null){
//process your jsonarray to get the Globals.PUBLIC_KEY)here
Log.v("onBackgroundTaskCompleted", "Public KEY JSON from OnStart" + Globals.PUBLIC_KEY);
//Start Activity
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}else{
Toast.makeText(mContext, "Network is unavailable. Request failed", Toast.LENGTH_LONG).show();
}
}
}
Gd Luck :)
The log from OnStart should return a null value for Globals.PUBLIC_KEY. You have just set an asynchronous task to run to set that value. It has not run yet by the time that log statement executes. You should receive the log input from the
Log.v(TAG, "JSON FROM NQRequest" + data);
call. That will mostly happen after your activity has finished onCreate, as it is an asynchronous call.
Fixed it works now.
public class HQHandler extends AsyncTask<String, Void, JSONArray> {
public static final String TAG = HQHandler.class.getSimpleName();
private static HQHandler instance;
RequestListener requestListener;
JSONArray requestResult;
Context mContext;
public HQHandler(Context context) {
this.mContext = context;
}
public static synchronized HQHandler getInstance(Context context) {
if (instance == null)
instance = new HQHandler(context);
return instance;
}
public void setRequestListener(RequestListener requestListener) {
this.requestListener = requestListener;
}
public JSONArray getRequestResult() {
return this.requestResult;
}
#Override
protected JSONArray doInBackground(String... params) {
try {
String url = "http://www.someurl.com";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
List<NameValuePair> urlParameters = requestHandlerHelper(params);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(urlParameters);
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8"));
post.setEntity(entity);
HttpResponse response = client.execute(post);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
Reader reader = new InputStreamReader(response.getEntity().getContent());
int contentLength = (int) response.getEntity().getContentLength();
Log.v(TAG, "Content Length DATA" + contentLength);
char[] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
JSONArray jsonResponse = new JSONArray(responseData);
return jsonResponse;
} catch (ClientProtocolException e) {
Log.i(TAG, "ClientProtocolException: ", e);
} catch (UnsupportedEncodingException e) {
Log.i(TAG, "UnsupportedEncodingException: ", e);
} catch (IOException e) {
Log.i(TAG, "IOException: ", e);
} catch (JSONException e) {
Log.i(TAG, "JSONException: ", e);
}
return null;
}
#Override
protected void onPostExecute(JSONArray results) {
if (results != null) {
requestListener.onRequestSuccess(results);
} else {
requestListener.onRequestFailed();
}
}
public interface RequestListener {
JSONArray onRequestSuccess(JSONArray data);
void onRequestFailed();
}
public JSONArray HQRequest(String... params) throws ExecutionException, InterruptedException, JSONException {
JSONArray result;
if (!isNetworkAvailable()) {
Toast.makeText(mContext, "Network is unavailable", Toast.LENGTH_LONG).show();
return null;
}
HQHandler handler = new HQHandler(this.mContext);
RequestListener listen = new RequestListener() {
#SuppressWarnings("unchecked")
#Override
public JSONArray onRequestSuccess(JSONArray data) {
return data;
}
#Override
public void onRequestFailed() {
Toast.makeText(mContext, "Network is unavailable. Request failed", Toast.LENGTH_LONG).show();
}
};
handler.setRequestListener(listen);
result = this.requestResult = handler.execute(params).get();
return result;
}
}

Categories