cant set text in postExecute ,Async, Android - java

I am not able to find any appropriate solution for below issue. I am using AsyncTask app sends request to server and it returns the JSON array as response, in postExecute method I parsed it, and problem is when I try to set the parsed data to TextView, textview not showing data. I am sure that server returned some data, and this data was parsed in postExecute and saved in global variables. TextViews also was declared as global variables, and defined in OnCreate method. thanks in advance!
Please check Code mentioned below:
public class CompanyData extends AppCompatActivity implements View.OnClickListener {
Button cComments;
String ssid,bin;
String extra, extra1;
TextView compData1, compData2, compData3, compData4, compData5, compData6, compTitle;
String title, kod_okpo, address, reg_date, fio, kod_oked, ovd ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_company_data);
cComments = (Button) findViewById(R.id.cComment);
cComments.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
extra = extras.getString("bin");
extra1 = extras.getString("ssid");
send_company_req(extra1, extra);
}
compTitle = (TextView) findViewById(R.id.companyTitle);
compData1 = (TextView) findViewById(R.id.compData1);
compData2 = (TextView) findViewById(R.id.compData2);
compData3 = (TextView) findViewById(R.id.compData3);
compData4 = (TextView) findViewById(R.id.compData4);
compData5 = (TextView) findViewById(R.id.compData5);
compData6 = (TextView) findViewById(R.id.compData6);
//Toast.makeText(this,"LOOOL" + title+bin+kod_okpo+address+reg_date+fio+kod_oked+ovd, Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.cComment:
Intent companyData = new Intent(CompanyData.this, Comments.class);
companyData.putExtra("bin", bin);
companyData.putExtra("ssid", ssid);
startActivity(companyData);
startActivity(new Intent(this, Comments.class));
break;
}
}
private void send_company_req(final String ssid, final String searchData) {
class GetJSON extends AsyncTask<String, String, String> {
ProgressDialog loading;
String rStr;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(CompanyData.this, "Request...", null, true, true);
}
#Override
protected String doInBackground(String... params) {
String token = params[0];
String fi = params[1];
String uri = Quickstart.URL + "/car/info";
String param = null;
try {
param = "ssid=" + URLEncoder.encode(token, "UTF-8") +
"&bin=" + URLEncoder.encode(fi, "UTF-8") + "&dev=android";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setFixedLengthStreamingMode(param.getBytes().length);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Authorization", "Bearer " + token);
PrintWriter out = new PrintWriter(con.getOutputStream());
out.print(param);
out.close();
String response = "";
Scanner inStream = new Scanner(con.getInputStream());
while (inStream.hasNextLine()) {
response += (inStream.nextLine());
}
return response;
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
//Toast.makeText(CompanyData.this, s, Toast.LENGTH_LONG).show();
JSONArray jsonArrayComp;
try {
jsonArrayComp = new JSONArray(s.trim());
JSONObject jsonObjectComp = jsonArrayComp.getJSONObject(0);
try {
title = jsonObjectComp.getString("title");
kod_okpo = jsonObjectComp.getString("kod_okpo");
address = jsonObjectComp.getString("address");
reg_date = jsonObjectComp.getString("reg_date");
fio = jsonObjectComp.getString("fio");
kod_oked = jsonObjectComp.getString("kod_1_oked");
ovd = jsonObjectComp.getString("vidd");
Toast.makeText(CompanyData.this,"LOOOL" + title+bin+kod_okpo+address+reg_date+fio+kod_oked+ovd, Toast.LENGTH_LONG).show();
} catch (Exception ee) {
}
} catch (Exception e) {
//Toast.makeText(CompanyData.this, "Упс,:( что то пошло не так, попробуйте еще раз пожалуйста.", Toast.LENGTH_SHORT).show();
}
compTitle.setText(title);
compData1.setText(bin);
compData2.setText(kod_okpo);
compData3.setText(address);
compData4.setText(reg_date);
compData5.setText(fio);
compData6.setText(kod_oked + " - " + ovd);
}
}
GetJSON gj = new GetJSON();
gj.execute(ssid, searchData);
}
}

Related

Android - Problem with executing AsyncTask thread

I'm trying to write an app that sends a POST request on asynchronous task. My AsyncTask does not seem to execute since my progress bar doesn't show up. I don't really know what is wrong here, since I followed many solutions/tutorials.
Here's my code:
register.java
public class register extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
final Activity thisActivity = this;
final EditText userNameEditText = findViewById(R.id.registerUsername);
final EditText emailEditText = findViewById(R.id.registerEmail);
final EditText passwordEditText = findViewById(R.id.registerPassword);
final ProgressBar progressBar = findViewById(R.id.progressBar);
Button btnRegisterDB = findViewById(R.id.btnRegistrationDB);
final TextView respondText = findViewById(R.id.responseRegister);
btnRegisterDB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String username = String.valueOf(userNameEditText.getText());
String email = String.valueOf(emailEditText.getText());
String password = String.valueOf(passwordEditText.getText());
//execute asynchronous task in background and wait for response
RegisterParams params = new RegisterParams(username, email, password);
registrationDB async = new registrationDB();
async.setProgressBar(progressBar);
async.setRespondText(respondText);
async.getParentActivity(thisActivity);
async.execute(params);
}
});
}
public boolean onOptionsItemSelected(MenuItem item){
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
return true;
}
public static class RegisterParams {
public String username;
public String email;
public String password;
RegisterParams(String username, String email, String password){
this.username = username;
this.email = email;
this.password = password;
}
}
}
and here is registrationDB.java
public class registrationDB extends AsyncTask<register.RegisterParams, Void, String> {
openHTTP openHTTP = new openHTTP();
String respond;
ProgressBar pb;
TextView respondTextView;
Activity parentActivity;
public void setProgressBar(ProgressBar progressBar){
this.pb = progressBar;
}
public void setRespondText(TextView textView){
this.respondTextView = textView;
}
public void getParentActivity(Activity parentActivity){
this.parentActivity = parentActivity;
}
#Override
public void onPreExecute(){
pb.setVisibility(View.VISIBLE);
//parentActivity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
// WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
super.onPreExecute();
}
#Override
protected String doInBackground(register.RegisterParams... params) {
try {
HttpURLConnection httpConn = openHTTP.prepareConnection("someurl");
String jsonInputString = "{ username: " + params[0].username +", email: " + params[0].email
+ ", password: " + params[0].password + "}";
try(OutputStream os = httpConn.getOutputStream()) {
byte[] input = jsonInputString.getBytes("utf-8");
os.write(input, 0, input.length);
} catch (Exception e){
e.printStackTrace();
}
try(BufferedReader br = new BufferedReader(
new InputStreamReader(httpConn.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
respond = response.toString();
return respond;
} catch (Exception e){
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
pb.setVisibility(View.GONE);
respondTextView.setText(s);
super.onPostExecute(s);
}
}
and I have external class openHTTP.java which is responsible for opening HttpUrlConnection:
public class openHTTP {
public openHTTP(){
}
//provide URL to external file that you want make POST request to
public HttpURLConnection prepareConnection(String URL){
try {
java.net.URL url = new URL(URL);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json; utf-8");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
return con;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Thanks in advance for help!
UPDATE
After logging processes I've discovered that exception:
java.io.IOException: Cleartext HTTP traffic to url not permitted, now I'm on my way searching for this problem
MY SOLUTION
So, it was enough to add android:usesCleartextTraffic="true" in AndroidManifest.xml
Thanks for your help!
After logging processes I've discovered that exception: java.io.IOException: Cleartext HTTP traffic to url not permitted.
So, it was enough to add android:usesCleartextTraffic="true" in AndroidManifest.xml Thanks for your help!

JSONParser: IOException: Unable to resolve host "my host address": No address associated with hostname

I am trying to get data from a JSON file that was written in a PHP file which was stored in my online hosting server(00webhost.com). When I run my program it says unknown host. However, the address will give JSON formatted file.
I have all the permissions along with the internet permission in my AndroidManifest.xml file.
Activity Class :
public class Recmain extends AppCompatActivity {
private String TAG = MainActivity.class.getSimpleName();
private ListView lv;
ArrayList<HashMap<String, String>> contactList;
TextView uid;
TextView name1;
TextView email1;
Button Btngetdata;
//URL to get JSON Array
private static String url = "http://tongue-tied-
papers.000webhostapp.com/data_fetch.php";
//JSON Node Names
private static final String TAG_USER = "user";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
JSONArray user = null;
private List<movie> movieList = new ArrayList<>();
private RecyclerView recyclerView;
private moviesadapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rmain);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent=getIntent();
String m=intent.getStringExtra("data");
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mAdapter = new moviesadapter(movieList);
RecyclerView.LayoutManager mLayoutManager = new
LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
prepareMovieData();
}
private void prepareMovieData(){
movie movie = new movie("Mad Max: Fury Road", "Action & Adventure",
"2015");
movieList.add(movie);
mAdapter.notifyDataSetChanged();
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(recmain.this,url,Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
JSONParser sh = new JSONParser();
// Making a request to url and getting response
String url = "https://tongue-tied-
papers.000webhostapp.com/data_fetch.php";
String jsonStr = sh.makeServiceCall(url);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("id");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
Toast.makeText(getApplicationContext(), id ,
Toast.LENGTH_LONG).show();
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat
for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
}
Adapter class:
public class JSONParser {
private static final String TAG = JSONParser.class.getSimpleName();
public JSONParser() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection)
url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new
InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
It says, unknown host.
Looks like the URL is not formatted correctly. I think there is a space between the two parts of the URL.
private static String url = "http://tongue-tied-papers.000webhostapp.com/data_fetch.php"
Please try with the URL above without any space between the tied- and papers. You have two separate URL declaration, one at the beginning of the class and the other is in the doInBackground method. Please try changing both.

How to acces TextView From another class

I've got my main startup class loading MainActivity but I'm trying to figure out how to access the TextView from another class which is loading information from a database. I would like to publish that information to the TextView.
private class DateValidation extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//Showing progress dialog
}
#Override
protected String doInBackground(String... arg0) {
String hallId = arg0[0];
String date = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?id=" + URLEncoder.encode(hallId, "UTF-8");
data += "&date=" + URLEncoder.encode(date, "UTF-8");
link = "https://www.adoetech.co.tz/ehall/frontend/index.php/hall/validate-date" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
Log.d("postData: ", link);
return result;
} catch (Exception e) {
return "Exception: " + e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
try {
JSONObject jsonObj = new JSONObject(result);
boolean query_result = jsonObj.getBoolean("success");
String response = jsonObj.getString("data");
if (query_result) {
Toast.makeText(HallsDetails.this, response, Toast.LENGTH_LONG).show();
} else if (!query_result) {
Log.d("onPostExecute: ", "free");
Toast.makeText(HallsDetails.this, response, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(HallsDetails.this, response, Toast.LENGTH_SHORT).show();
//JSONArray dateVal = jsonObj.getJSONArray("data");
I need to setTest from here and I have declear hallPrice from MainActivity help Please
hallPrice.setText("300000000");
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("onPostExecute: ", String.valueOf(result));
Toast.makeText(HallsDetails.this, "Error parsing JSON data.", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(HallsDetails.this, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}
}
}
Use intent to pass data from one activity to another like this:-
Intent in = new Intent(MainActivity.this, DateValidation.class);
in.putExtra("key", "300000000");
startActivity(in);
And in your DateValidation Activity do:-
Intent i = getIntent();
String value = i.getStringExtra("key");
hallPrice.setText(value);
You can pass the TextView in your AsyncTask.
public class DateValidation extends AsyncTask<String,String,String> {
TextView mTextView;
public DateValidation (TextView textView){
mTextView = textView;
}
#Override
protected String doInBackground(String... strings) {
/**
* do process here
*/
return "Result String here";
}
#Override
protected void onPostExecute(String result) {
mTextView.setText(result);
}
}

how to convert a .execute to just display right away on textview instead

adminpage.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_page);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mTextView = (TextView) findViewById(R.id.dataList);
Button button = (Button) findViewById(R.id.rf);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// new JSONTask().execute("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoItem.txt");
new JSONTask().execute("https://jsonparsingdemo-cec5b.firebaseapp.com/jsonData/moviesDemoList.txt");
}
});
}
public static class JSONTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("movies");
StringBuffer finalBufferedData = new StringBuffer();
for (int i = 0; i < parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
String movieName = finalObject.getString("movie");
int year = finalObject.getInt("year");
finalBufferedData.append(movieName + " - " + year + "\n");
}
//JSONObject finalObject = parentArray.getJSONObject(0);
return finalBufferedData.toString();
//return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mTextView.setText(result);
}
}
So base on this what i can conclude is.
1) JSONTASK will take the url and break them in to different string and link them together and return finalBufferedData.toString();
2) The onPostExecute will take the result and set it to mTextView.
3) onclicklistener will run the function and perform step 2 and display.
Question!
I don't see anywhere in the code that call the function onPostExecute(String result) <-- what is the result?? is it the return finalBufferedData.toString()?
I am running the same function in another activity, how do i display in TextView without the onClicklistener to execute it.
1. Yes.. it is the return value(finalBufferedData.toString()).It is the output (result/return) of doInBackground method.
2. Call in onCreate or onResume for executing without onClick. eg:-
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
// put the AsyncTask call here

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

Categories