tazeenmulani tazeenmulani - 5 months ago 9
Android Question

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

Answer

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

enter image description here

Comments