Get value from Async task in Activity - java

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

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.

onPostExecute() doesn't start

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;

JSON: Value of type java.lang.String cannot be converted to JSONObject

I'm trying to program an app to send a String to a service. A friend of mine has a service to receive the data.
Logcat shows this error: "org.json.JSONException: Value FIRST of type java.lang.String cannot be converted to JSONObject"
Here is my code:
Main Activity
public class MainActivity extends Activity {
private String URL = "String with my friend's url";
private Button btnAddValue;
String num = "1";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RadioGroup answer = (RadioGroup) findViewById(R.id.answer);
answer.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch (checkedId) {
case R.id.answerA:
num = "1";
break;
case R.id.answerB:
num = "2";
break;
case R.id.answerC:
num = "3";
break;
}
}
});
btnAddValue = (Button) findViewById(R.id.submit);
btnAddValue.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
new AddNewValue().execute(num);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
private class AddNewValue extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... arg) {
// TODO Auto-generated method stub
String number = arg[0];
// Preparing post params
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("number", number));
ServiceHandler serviceClient = new ServiceHandler();
String json = serviceClient.makeServiceCall(URL,
ServiceHandler.POST, params);
Log.d("Create Request: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
boolean error = jsonObj.getBoolean("error");
// checking for error node in json
if (!error) {
// new category created successfully
Log.e("Value added successfully ",
"> " + jsonObj.getString("message"));
} else {
Log.e("Add Error: ",
"> " + jsonObj.getString("message"));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "JSON data error!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
Service Handler
public class ServiceHandler {
static InputStream is = null;
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
response = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error: " + e.toString());
}
return response;
}
}
I read questions to other people with the same problem. The solution seemed to be to add a "{" at the beginning of the json String and a "}" at the end, but it didn't work to me. I tried changing this:
String json = serviceClient.makeServiceCall(URL_NEW_PREDICTION,
ServiceHandler.POST, params);
to this:
String json = "{" + serviceClient.makeServiceCall(URL_NEW_PREDICTION,
ServiceHandler.POST, params) + "}";
but the I got this error:
"org.json.JSONException: Expected ':' after FIRST at character 9 of {FIRST DATA New record created successfully}"
You're receiving back a string that is not able to be parsed to JSON. You can't just make something JSON by adding braces, it needs to adhere to proper JSON formatting. This site shows some good examples of what that means.
Specifically, the parser is telling you that having a space after FIRST isn't okay without having quotes around it...but just adding that won't fix the issue, the problem is more deep than that.

How to integrate with jsonwebservices in Android?

I'm implementing json_web services in my Android application. I want to send the json data on jsonwebservices which is created in Java. When I run the application data does not send from the Android and does not show any error and also does not show any type of exception.
How can I identify whether my data is sent or not?
Here is my Activity Code:
public class Login extends Activity
{
Button btnLogin;
EditText etextUsername , etextPassword;
String strUserName , strPassWord ;
ProgressDialog pDialog;
JSONObject jObject ;
SharedPreferences.Editor editor;
SharedPreferences sharedPref1;
String str_Device_IP_Address=null;
JSONArray user = null;
String pref_filename = "IP_ADDRESS";
static final String KEY_REQUEST_ID = "RequestId";
static final String KEY_REQUEST_CODE = "RequestCode";
static final String KEY_CHANNEL_ID = "ChannelId";
static final String KEY_IP_ADDRESS="IPAddress";
static final String KEY_USERNAME="UserId";
static final String KEY_PASSWORD="Password";
static final String KEY_REQUEST="Request";
static final String KEY_VENDOR_ID="VendorId";
String RequestId="77777";
String RequestCode="001";
String stringChannelId="MobileApp";
String strIpAddress = null;
private String textToEncrypt = "Hi, this is a test to check its gone work or not.";
String encrypted = "MzA3RDBCMjMxMjQzNzcxREUxMUYxNjg1NzgwOTU1MjU1M0FDOUZEN0M3Q0JGQ0Q5MTI2NEIyNTE2"
+ "OTQwQTc3NjM2QTBCRDFDMUEyNkUwRjlDMzQwN0U0MEI0NDg2M0JBMDU1OThCNTI1NTZCMEFGNjk1NjJFNzZBMUE0NzM4NTQ=";
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
final Context context = getApplicationContext();
connectWithHttpGet_IpAddress();
etextUsername = (EditText)findViewById(R.id.edittext_username);
etextPassword = (EditText)findViewById(R.id.edittext_password);
btnLogin=(Button)findViewById(R.id.button_Login);
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if (!isOnline())
{
showNoConnectionDialog(Login.this);
}
else
{
connectWithHttpGet_LoginData();
}
}
});
}
private void connectWithHttpGet_LoginData()
{
class GetJSONParse extends AsyncTask<String, Integer, JSONObject>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
str_Device_IP_Address=sharedPref1.getString("ip_address", "a\n");
System.out.println("strCode in Gsk_Demo ="+str_Device_IP_Address);
strUserName = etextUsername.getText().toString().trim();
strPassWord = etextPassword.getText().toString().trim();
pDialog = new ProgressDialog(Login.this);
pDialog.setIndeterminate(true);
pDialog.setCancelable(true);
pDialog.show();
System.out.println("Progress Dialog!!!!!!!!!!!!!!!!!!!!!!!");
}
#Override
protected JSONObject doInBackground(String... args)
{
String strUrl = "http://test.xxxxxx.com/cms/json/w2iWS";
JSONParser jParser = new JSONParser();
Log.e("DoinBackground !!!!!","Method");
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(strUrl);
String jsonString=json.toString();
Log.e("jsonString in DoinBackground !!!!!","Method" + jsonString);
return json;
}
#Override
protected void onPostExecute(JSONObject json)
{
pDialog.dismiss();
try
{
// Getting JSON Array
user = json.getJSONArray( KEY_REQUEST_ID );
JSONObject jsonObject = user.getJSONObject(0);
jsonObject.put(KEY_REQUEST_CODE, RequestCode);
jsonObject.put(KEY_CHANNEL_ID, stringChannelId);
jsonObject.put(KEY_IP_ADDRESS, str_Device_IP_Address);
jsonObject.put(KEY_USERNAME, strUserName);
jsonObject.put(KEY_PASSWORD, strPassWord);
String encrypted1 = EncodeDecodeAES.encrypt(jsonObject.toString(), textToEncrypt);
System.out.println("encrypted1 =" + encrypted1);
JSONObject inner = new JSONObject();
inner.put(KEY_REQUEST, encrypted1);
inner.put(KEY_VENDOR_ID, "1");
String decrypted = EncodeDecodeAES.decrypt(jsonObject.toString(), encrypted);
System.out.println("decrypted =" + decrypted);
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
GetJSONParse getjsonparse = new GetJSONParse();
getjsonparse.execute();
}
// Get Ip Address
private void connectWithHttpGet_IpAddress() {
class httpGetAsynchTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpClient httpClient = new DefaultHttpClient();
String url = "http://api.externalip.net/ip";
Log.e("!!STRING URL DATE DETAIL", "" + url);
HttpGet httpGet = new HttpGet(url);
Log.e("", "" + httpGet);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
Log.e("HTTP.RESPONSE.DATE.DTAIL", "" + httpResponse);
System.out.println("HTTPRESPONSE");
InputStream inpustream = httpResponse.getEntity()
.getContent();
InputStreamReader inputstreamreader = new InputStreamReader(
inpustream);
BufferedReader bufferedreader = new BufferedReader(
inputstreamreader);
StringBuilder stringbuilder = new StringBuilder();
Log.e("", "" + stringbuilder);
String strbuffer = null;
while ((strbuffer = bufferedreader.readLine()) != null)
{
stringbuilder.append(strbuffer);
}
String strResponse = stringbuilder.toString();
/****************** Code For Shared Preferences **************************************/
sharedPref1 = getSharedPreferences(pref_filename, 0);
editor = sharedPref1.edit();
editor.putString("ip_address", strResponse);
Log.e("Returning value of doInBackground REsponse:" ,strResponse);
System.out.println("IPADDRESS IN DOIN BACKGRAOUND");
editor.commit();
/***************** Code For Shared Preferences **************************************/
}
catch (ClientProtocolException cpe) {
cpe.printStackTrace();
Log.e("Exception generates caz of httpResponse :", "-"
+ cpe);
}
catch (IOException ioe) {
ioe.printStackTrace();
Log.e("Second exception generates caz of httpResponse :",
"-" + ioe);
}
return null;
}
}
httpGetAsynchTask httpGetAsyncTask = new httpGetAsynchTask();
httpGetAsyncTask.execute();
}
public static void showNoConnectionDialog(final Login login)
{
AlertDialog.Builder builder = new AlertDialog.Builder(login);
builder.setCancelable(true);
builder.setMessage(R.string.no_connection);
builder.setTitle(R.string.no_connection_title);
builder.setPositiveButton(R.string.settings_button_text, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
login.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
});
builder.setNegativeButton(R.string.cancel_button_text, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
return;
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
#Override
public void onCancel(DialogInterface dialog) {
return;
}
});
builder.show();
}
public boolean isOnline()
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected())
{
return true;
}
else
{
return false;
}
}
}
Asynctask is not invoked
JSONParse jp =new JSONParse();
jp.execute(params);
http://developer.android.com/reference/android/os/AsyncTask.html
public final AsyncTask<Params, Progress, Result> execute (Params... params)
Executes the task with the specified parameters.
You had no invoked asynctask before
GetJSONParse get = new GetJSONParse();
get.execute(params);
And you said i can't see the log message in doInbackground. i just ran your code and i can see the log

http get in android

i have the following android code , i have an sms broadcast receiver in a service that waits for in coming sms, then on receiving it, it shows a toast, then it is supposed to make a get request to the specified url ,everything works as expected but the upload message action is not taking place, stumped here .
public class ReceiverContainer extends Service{
public SMSreceiver mSMSreceiver;
public IntentFilter mIntentFilter;
#Override
public void onCreate()
{
super.onCreate();
//SMS event receiver
mSMSreceiver = new SMSreceiver();
mIntentFilter = new IntentFilter();
mIntentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(mSMSreceiver, mIntentFilter);
}
#Override
public void onDestroy()
{
super.onDestroy();
// Unregister the SMS receiver
unregisterReceiver(mSMSreceiver);
mSMSreceiver = null;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public class SMSreceiver extends BroadcastReceiver
{
public void Action(Context context,Intent intent) throws ClientProtocolException, URISyntaxException, IOException
{
Bundle myBundle = intent.getExtras();
SmsMessage [] messages = null;
String strMessage = "";
String msgFrom = "";
String msgText = "";
if (myBundle != null)
{
Object [] pdus = (Object[]) myBundle.get("pdus");
messages = new SmsMessage[pdus.length];
for (int i = 0; i < messages.length; i++)
{
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
strMessage += "SMS From: " + messages[i].getOriginatingAddress();
msgFrom += messages[i].getOriginatingAddress();
strMessage += " : ";
strMessage += messages[i].getMessageBody();
msgText += messages[i].getMessageBody();
strMessage += "\n";
}
Toast.makeText(context, strMessage, Toast.LENGTH_SHORT).show();
uploadMessage(context,msgFrom,msgText);
}
}
#Override
public void onReceive(Context context, Intent intent)
{
try {
Action(context,intent);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void uploadMessage(Context context,String number,String msg) throws URISyntaxException, ClientProtocolException, IOException
{
HttpResponse response = null;
HttpClient client = new DefaultHttpClient();
Uri.Builder path = new Uri.Builder();
path.scheme("http");
path.authority("technonectar11.com");
path.path("sms");
path.appendQueryParameter("fromno" , number);
path.appendQueryParameter("text" , msg);
path.appendQueryParameter("uname" , "vijay");
HttpGet request = new HttpGet(path.build().toString());
//request.setURI(new URI("http://www.technonectar11.com/sms/insertsms?fromno="+number+"&text="+msg+"&uname=vijay"));
response = client.execute(request);
String result = convertStreamToString(response.getEntity().getContent());
Toast.makeText(context, result, Toast.LENGTH_SHORT).show();
}
public static String convertStreamToString(InputStream inputStream) throws IOException
{
if (inputStream != null)
{
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try
{
Reader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"),1024);
int n;
while ((n = reader.read(buffer)) != -1)
{
writer.write(buffer, 0, n);
}
}
finally
{
inputStream.close();
}
return writer.toString();
}
else
{
return "";
}
}
}
You are not allowed to make internet requests on the main thread.
Use AsyncTasks to make the request.
Declare INTERNET PERMISSION IN manfiest file
try HttpPost
httpclient=new DefaultHttpClient();
HttpPost httppost=new HttpPost(URL);
HttpResponse res = null;
try {
res = httpclient.execute(httppost);
System.out.println("asa "+res);
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}

Categories