How to dismiss progress bar once otp read from Inbox in android? - android

I have a Otp verification Screen in which I have a progress bar with timer ,what I want is to dismiss this progressbar once Read Otp from inbox if read successfully from Inbox then dismiss progressbar and execute Jsons Url if not then show progressbar with timer until not read sms from Inbox.for this I am using Broadcast Receiver .Kindly help me .
here is my code of MainActivity :-
public class COtpAutoVerificationScreen extends Fragment {
private static String s_szResult = "";
private final String m_szOTPVERIFICATIONURL = "http://202.131.144.132:8080/resting/rest/json/metallica/validateOTPInJSON";
public ProgressBar pb;
private View m_Main;
private int m_n_ProgressStatus = 0;
private CRegistrationSessionManagement m_oSessionManagement;
private String m_szMobileNumber;
private String m_szEncryptedPassword;
private CircularProgressView m_ProgressView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
m_Main = inflater.inflate(R.layout.otp_auto_verified, container, false);
getUserDetails();// getuser deatails....
init();// initialize controls...
return m_Main;
}
private void getUserDetails() {
m_oSessionManagement = new CRegistrationSessionManagement(getActivity());
}
private void init() {
m_ProgressView = (CircularProgressView) m_Main.findViewById(R.id.progress_view);
m_ProgressView.startAnimation();
m_ProgressView.setVisibility(View.GONE);
pb = (ProgressBar) m_Main.findViewById(R.id.pb);
final TextView tv = (TextView) m_Main.findViewById(R.id.tv);
#SuppressWarnings("UnusedAssignment") final TextView validationText = (TextView) m_Main.findViewById(R.id.validatingmessage);
tv.setText("00:00");
//Initialize a new CountDownTimer instance
long m_MillisInFuture = 30000;
long m_CountDownInterval = 1000;
new CountDownTimer(m_MillisInFuture, m_CountDownInterval) {
public void onTick(long millisUntilFinished) {
#SuppressWarnings("UnusedAssignment") long millis = millisUntilFinished;
String hms = String.format("%02d:%02d", TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished)));
System.out.println(hms);
tv.setText(hms);
//Another one second passed
//Each second ProgressBar progress counter added one
m_n_ProgressStatus += 1;
pb.setProgress(m_n_ProgressStatus);
}
public void onFinish() {
// retreive user data from shared preferencce........
HashMap<String, String> user = m_oSessionManagement.getRegistrationDetails();
m_szEncryptedPassword = user.get(CRegistrationSessionManagement.s_szKEY_PASSWORD).trim();
m_szMobileNumber = user.get(CRegistrationSessionManagement.s_szKEY_MOBILENUMBER).trim();
// exc=ecuting request for otp verfiifcation to server
new COtpVerify().execute();
}
}.start();
// retreive progress bar count........
int progressBarMaximumValue = (int) (m_MillisInFuture / m_CountDownInterval);
//Set ProgressBar maximum value
//ProgressBar range (0 to maximum value)
pb.setMax(progressBarMaximumValue);
//Display the CountDownTimer initial value
tv.setText(progressBarMaximumValue + "Seconds...");
}
// sending OTP to server to verify Otp
private class COtpVerify extends AsyncTask<String, Void, String> {
public JSONObject m_oResponseobject;
public String m_szResponseAgentCode;
#Override
protected void onPreExecute() {
super.onPreExecute();
m_ProgressView.setVisibility(View.VISIBLE);
}
#SuppressWarnings("deprecation")
#Override
protected String doInBackground(String... args) {
InputStream inputStream;
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(m_szOTPVERIFICATIONURL);
String json;
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.put("agentCode", m_szMobileNumber);
jsonObject.put("pin", m_szEncryptedPassword);
jsonObject.put("otpCode", COTPVerificationDataStorage.getInstance().getM_szOtp());
// 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("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
// 9. receive response as inputStream
inputStream = entity.getContent();
System.out.print("InputStream...." + inputStream.toString());
System.out.print("Response...." + httpResponse.toString());
StatusLine statusLine = httpResponse.getStatusLine();
System.out.print("statusLine......" + statusLine.toString());
////Log.d("resp_body", resp_body.toString());
int statusCode = statusLine.getStatusCode();
// 10. convert inputstream to string
if (statusCode == 200) {
// 10. convert inputstream to string
s_szResult = CJsonsResponse.convertInputStreamToString(inputStream);
//String resp_body =
} else
s_szResult = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
System.out.println("resul" + s_szResult);
// 11. return s_szResult
return s_szResult;
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(final String result) {
m_ProgressView.setVisibility(View.GONE);
try {
m_oResponseobject = new JSONObject(result);// getting response from server
getResponse();// getting response from server ...............
} catch (Exception e) {
e.printStackTrace();
}
}
public void getResponse() throws JSONException {
// if server response is successfull then......
if (m_oResponseobject.getString("resultDesc").equalsIgnoreCase("Transaction Successful")) {
// if server response is success then setting response odata in shared prefernce...
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CLoginScreen()).commit();
CSnackBar.getInstance().showSnackBarSuccess(m_Main.findViewById(R.id.mainLayout), "OTP verified successfully", getActivity());
}
// if response from server is m_szOtp mismatch.....
else if (m_oResponseobject.getString("resultDesc").equalsIgnoreCase("OTP MisMatch")) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "OTP not found", getActivity());
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new COtpManualVerificationScreen()).commit();
}
}, 3000);
}
// if response from server is m_szOtp empty then......
else if (m_oResponseobject.getString("resultDesc").equalsIgnoreCase("otpCode Can Not Be Empty")) {
CSnackBar.getInstance().showSnackBarError(m_Main.findViewById(R.id.mainLayout), "OTP not found", getActivity());
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new COtpManualVerificationScreen()).commit();
}
}, 3000);
}
}
}
}
and here is my BroadcastReceiver class:-
public class CSmsBroadcastReceiver extends BroadcastReceiver {
private static final String s_szTAG = CSmsBroadcastReceiver.class.getSimpleName();
private static String m_szOtpCode;
#Override
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
Object[] pdusObj = (Object[]) bundle.get("pdus");
assert pdusObj != null;
for (Object aPdusObj : pdusObj) {
#SuppressWarnings("deprecation") SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) aPdusObj);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String message = currentMessage.getDisplayMessageBody();
Log.e(s_szTAG, "Received SMS: " + message + ", Sender: " + phoneNumber);
// checking sms sender address....
if (phoneNumber.toLowerCase().contains("+919971599707".toLowerCase())) {
// verification code from sms
m_szOtpCode = getVerificationCode(message);
assert m_szOtpCode != null;
String input = m_szOtpCode.trim();
Log.e(s_szTAG, "OTP received: " + m_szOtpCode);
COTPVerificationDataStorage.getInstance().setM_szOtp(input);// getting otp from SMS and set to otpverificationstorage class
} else {
return;
}
}
}
} catch (Exception e) {
Log.e(s_szTAG, "Exception: " + e.getMessage());
}
}
/**
* Getting the OTP from sms message body
* ':' is the separator of OTP from the message
*
* #param message
* #return
*/
#SuppressWarnings("JavaDoc")
private String getVerificationCode(String message) {
String code;
int index = message.indexOf(":");
if (index != -1) {
int start = index + 2;
int length = 6;
code = message.substring(start, start + length);
return code;
}
COTPVerificationDataStorage.getInstance().setM_szOtp(m_szOtpCode);
return null;
}
}

Basically you want to send data from broadcast receiver to activity whenever desired message comes.you can make use of interface to communicate
In you BroadcastReceiver create interface like this
public interface OnSmsReceivedListener {
public void onSmsReceived(String message);
}
add one method to initialize interface reference
OnSmsReceivedListener smsListener;
public void setOnSmsReceivedListener(Context context) {
this.smsListener = (OnSmsReceivedListener) context;
}
use this reference to call function inside onReceive() method
smsListener.onSmsReceived("Message Received!!!");
You are done with posting data ,now give implementation of interface in your Activity and dismiss your dialog.
public class SampleActivity extends Activity implements OnSmsReceivedListener
#Override
public void onSmsReceived(String message) {
//Dismiss your dialog here
}
Other then this approach you can make use of some good third party library like EventBus and Otto which will make your work simple and easy.

Related

How to use Handler in AsynkTask in android

I am fetching data from server using AsynkTask which works fine but I want to use handler in AsynkTask to reduce load from main Thread.How can I use Handler in AsynkTask. Kindly help me to solve this problem.
Here is my code.
public class CLoginScreen extends Fragment {
public static String s_szLoginUrl = "http://192.168.0.999:8080/rest/json/metallica/getLoginInJSON";
public static String s_szresult = " ";
public static String s_szMobileNumber, s_szPassword;
public static String s_szResponseMobile, s_szResponsePassword;
public View m_Main;
public EditText m_InputMobile, m_InputPassword;
public AppCompatButton m_LoginBtn, m_ChangePass, m_RegisterBtn;
public CJsonsResponse m_oJsonsResponse;
public boolean isFirstLogin;
public JSONObject m_oResponseobject;
public LinearLayout m_MainLayout;
public CLoginSessionManagement m_oLoginSession;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
m_Main = inflater.inflate(R.layout.login_screen, container, false);
((AppCompatActivity) getActivity()).getSupportActionBar().hide();
m_oLoginSession = new CLoginSessionManagement(getActivity());
init();
return m_Main;
}
public void init() {
m_MainLayout = (LinearLayout) m_Main.findViewById(R.id.mainLayout);
m_InputMobile = (EditText) m_Main.findViewById(R.id.input_mobile);
m_InputPassword = (EditText) m_Main.findViewById(R.id.input_password);
m_LoginBtn = (AppCompatButton) m_Main.findViewById(R.id.btn_Login);
m_ChangePass = (AppCompatButton) m_Main.findViewById(R.id.btn_ChangePass);
m_ChangePass.setBackgroundColor(Color.TRANSPARENT);
m_ChangePass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CChangePasswordScreen()).commit();
}
});
m_RegisterBtn = (AppCompatButton) m_Main.findViewById(R.id.btn_Register);
m_RegisterBtn.setBackgroundColor(Color.TRANSPARENT);
m_RegisterBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CRegistrationScreen()).commit();
}
});
m_LoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new LoginAttempt().execute();
}
});
}
private class LoginAttempt extends AsyncTask<String, Void, String> {
public Dialog m_Dialog;
public ProgressBar m_ProgressBar;
#Override
protected void onPreExecute() {
super.onPreExecute();
m_Dialog = new Dialog(getActivity());
m_Dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
m_Dialog.setContentView(R.layout.progress_bar);
showProgress("Please wait while Logging...");// showing progress ..........
}
#Override
protected String doInBackground(String... params) {
getLoginDetails();// getting login details from editText...........
InputStream inputStream = null;
m_oJsonsResponse = new CJsonsResponse();
isFirstLogin = true;
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(s_szLoginUrl);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.put("agentCode", s_szMobileNumber);
jsonObject.put("pin", s_szPassword);
jsonObject.put("firstloginflag", m_oLoginSession.isLogin());
// 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"); ///not required
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
// 9. receive response as inputStream
inputStream = entity.getContent();
System.out.print("InputStream...." + inputStream.toString());
System.out.print("Response...." + httpResponse.toString());
StatusLine statusLine = httpResponse.getStatusLine();
System.out.print("statusLine......" + statusLine.toString());
////Log.d("resp_body", resp_body.toString());
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
// 10. convert inputstream to string
if (inputStream != null) {
s_szresult = m_oJsonsResponse.convertInputStreamToString(inputStream);
//String resp_body =
EntityUtils.toString(httpResponse.getEntity());
}
} else
s_szresult = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
System.out.println("s_szResult....." + s_szresult);
System.out.println("password......" + s_szPassword);
// 11. return s_szResult
return s_szresult;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
hideProgress();// hide progressbar after getting response from server......
try {
m_oResponseobject = new JSONObject(response);// getting response from server
new Thread() {// making child thread...
public void run() {
Looper.prepare();
try {
getResponse();// getting response from server
Looper.loop();
} catch (JSONException e) {
e.printStackTrace();
}
}
}.start();
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getResponse() throws JSONException {
if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Transaction Successful")) {
m_oLoginSession.setLoginData(s_szResponseMobile, s_szResponsePassword);
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CDealMainListing()).commit();
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Agentcode Can Not Be Empty")) {
showToast("Please Enter Valid Mobile Number");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Pin Can Not Be Empty")) {
showToast("Please Enter Password");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Invalid PIN")) {
showToast("Invalid Password");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Blocked due to Wrong Attempts")) {
showToast("You are blocked as You finished you all attempt");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {
showToast("Connection Lost ! Please Try Again");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Not Found")) {
showToast("User not found ! Kindly Regiter before Login");
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("OTP not verify")) {
showToast("Otp not Verify ! Kindly Generate Otp on Sign Up");
}
}
public void showToast(String message) {// method foe showing taost message
Toast toast = Toast.makeText(getActivity(), "" + message, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
public void getLoginDetails() {
s_szMobileNumber = m_InputMobile.getText().toString();
s_szPassword = m_InputPassword.getText().toString();
}
public void showProgress(String message) {
m_ProgressBar = (ProgressBar) m_Dialog.findViewById(R.id.progress_bar);
TextView progressText = (TextView) m_Dialog.findViewById(R.id.progress_text);
progressText.setText("" + message);
progressText.setVisibility(View.VISIBLE);
m_ProgressBar.setVisibility(View.VISIBLE);
m_ProgressBar.setIndeterminate(true);
m_Dialog.setCancelable(false);
m_Dialog.setCanceledOnTouchOutside(false);
m_Dialog.show();
}
public void hideProgress() {
m_Dialog.dismiss();
}
}
}
As per android docs here
An asynchronous task is defined by a computation that runs on a
background thread and whose result is published on the UI thread.
And loading data from URL with Handler is not a good thing. Instead use Executor or ThreadPoolExecutor to do heavy background tasks.
You Can Use
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
getResponse();
}
});
you can do like this:
class MyAsyncTask extends AsyncTask<Object,Object,Object>{
Private Context c;
private Handler handler;
private final static int YOUR_WORK_ID = 0x11;
public MyAsyncTask(Context c,Handler handler){
this.c = c;
this.handler = handler;
}
protected Object doInBackground(Object... params){
//do your work
...
Message m = handler.obtainMessage();
m.what = YOUR_WORK_ID;
...
handler.sendMessage().sendToTarget();
}
}
And in your fragment ,you can init a handler as params to MyAsyncTask,and deal with you work in handleMessage();

How to update UI from separate AsynkTask class

I have a class CDealListing from where I execute AsynkTask class which is separate class,what I want is to update UI of class CDealListing on AsynkTask class onPost method .kindly help me .....
here is code of my class CDealListing
public class CDealAppListing extends Fragment {
public static String m_DealListingURL = "http://192.166.0.110:8080/ireward/rest/json/metallica/getDealListInJSON";
public static String s_szresult = " ";
public static RecyclerView m_RecyclerView;
public static CDealAppListingAdapter m_oAdapter;
public static CDealAppDatastorage item;
public ArrayList<CDealAppDatastorage> s_oDataset;
public int[] m_n_FormImage;
public View m_Main;
public CRegistrationSessionManagement m_oSessionManagement;
public String m_szMobileNumber, m_szEncryptedPassword;
public LinearLayoutManager mLayoutManager;
public AppCompatButton m_showMore;
public ProgressBar mProgressBar;
public int m_n_DefaultRecordCount = 5;// intiallly record count is 5.
public int m_n_DeafalutLastCount = 0;//initally lastcount is 0.
public String sz_RecordCount, sz_LastCount;
//declare boolean
private CJsonsResponse m_oJsonsResponse;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
m_Main = inflater.inflate(R.layout.deal_app_listing, container, false);//intialize mainLayout
new CDealDataSent().execute(m_DealListingURL);
init();//initialize method
implementScroll();
return m_Main;
}
public void init() {
mProgressBar = (ProgressBar) m_Main.findViewById(R.id.progressBar1);
mProgressBar.setVisibility(View.GONE);
m_showMore = (AppCompatButton) m_Main.findViewById(R.id.show_more);
m_showMore.setBackgroundColor(Color.TRANSPARENT);
m_showMore.setVisibility(View.GONE);
// Getting the string array from strings.xml
m_n_FormImage = new int[]{
R.drawable.amazon,
R.drawable.whatsapp,
R.drawable.zorpia,
R.drawable.path,
R.drawable.app_me,
R.drawable.evernote,
R.drawable.app_me};
m_RecyclerView = (RecyclerView) m_Main.findViewById(R.id.my_recycler_view);//finding id of recyclerview
m_RecyclerView.setItemAnimator(new DefaultItemAnimator());//setting default animation to recyclerview
m_RecyclerView.setHasFixedSize(true);//fixing size of recyclerview
mLayoutManager = new LinearLayoutManager(getActivity());
m_RecyclerView.setLayoutManager(mLayoutManager);//showing odata vertically to user.
m_oSessionManagement = new CRegistrationSessionManagement(getActivity());
HashMap<String, String> user = m_oSessionManagement.getRegistrationDetails();
m_szEncryptedPassword = user.get(m_oSessionManagement.s_szKEY_PASSWORD);
m_szMobileNumber = user.get(m_oSessionManagement.s_szKEY_MOBILENUMBER);
sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// increment of record count
sz_LastCount = String.valueOf(m_n_DeafalutLastCount);
}
public void implementScroll() {
m_RecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == RecyclerView.SCROLL_STATE_IDLE){
}
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (dy > 0) {
m_showMore.setVisibility(View.VISIBLE);
m_showMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//change boolean value
m_showMore.setVisibility(View.GONE);
m_n_DefaultRecordCount = m_n_DefaultRecordCount + 5;
m_n_DeafalutLastCount = m_n_DeafalutLastCount + 5;
sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);
sz_LastCount = String.valueOf(m_n_DeafalutLastCount);
new DealNext().execute(m_DealListingURL);
}
});
} else {
m_showMore.setVisibility(View.GONE);
}
}
});
}
//sending deal data to retreive response from server
public String DealListing(String url, CRegistrationDataStorage login) {
InputStream inputStream = null;
m_oJsonsResponse = new CJsonsResponse();
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.put("agentCode", m_szMobileNumber);
jsonObject.put("pin", m_szEncryptedPassword);
jsonObject.put("recordcount", sz_RecordCount);
jsonObject.put("lastcountvalue", sz_LastCount);
//jsonObject.put("emailId", "nirajk1190#gmail.com");
// 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("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
// 9. receive response as inputStream
inputStream = entity.getContent();
System.out.println("InputStream....:" + inputStream.toString());
System.out.println("Response....:" + httpResponse.toString());
StatusLine statusLine = httpResponse.getStatusLine();
System.out.println("statusLine......:" + statusLine.toString());
////Log.d("resp_body", resp_body.toString());
int statusCode = statusLine.getStatusCode();
// 10. convert inputstream to string
if (statusCode == 200) {
// 10. convert inputstream to string
if (inputStream != null)
s_szresult = m_oJsonsResponse.convertInputStreamToString(inputStream);
//String resp_body =
EntityUtils.toString(httpResponse.getEntity());
} else
s_szresult = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
System.out.println("resul.....:" + s_szresult);
// 11. return s_szResult
return s_szresult;
}
and here is my AsynkTask class
/ sending deal data to server and retreive response......
class CDealDataSent extends AsyncTask<String, Void, String> {
public JSONObject m_oResponseobject;
public ProgressDialog m_PDialog;
public CRegistrationDataStorage oRegisterStorage;
public CDealAppDatastorage item;
// #Override
protected void onPreExecute() {
super.onPreExecute();
m_PDialog = new ProgressDialog(getActivity());
m_PDialog.setMessage("Please wait while Loading Deals...");
m_PDialog.setCancelable(false);
m_PDialog.show();
}
#Override
protected String doInBackground(String... urls) {
return DealListing(urls[0], oRegisterStorage);// sending data to server...
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
m_PDialog.dismiss();
try {
m_oResponseobject = new JSONObject(result);// getting response from server
final JSONArray posts = m_oResponseobject.optJSONArray("dealList");
s_oDataset = new ArrayList<CDealAppDatastorage>();
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.getJSONObject(i);
item = new CDealAppDatastorage();
item.setM_szHeaderText(post.getString("dealname"));
item.setM_szsubHeaderText(post.getString("dealcode"));
item.setM_n_Image(m_n_FormImage[i]);
s_oDataset.add(item);
}
getResponse();
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getResponse() throws JSONException {
if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Transaction Successful")) {
m_oAdapter = new CDealAppListingAdapter(s_oDataset);//creating object of adapter and addd setting odata to adapter for use.
m_RecyclerView.setAdapter(m_oAdapter);//adding adapter to recyclerview
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {
Toast.makeText(getActivity(), "Connection not avaliable", Toast.LENGTH_SHORT).show();
}else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Deal List Not Found")){
Toast.makeText(getActivity(),"No More Deals",Toast.LENGTH_SHORT).show();
}
System.out.println("agentCode...." + m_szMobileNumber);
System.out.println("password...." + m_szEncryptedPassword);
System.out.println("record////" + sz_RecordCount);
System.out.println("last:........" + sz_LastCount);
}
}
In asynkTask class get Response method update UI of class CDealListing
There are 3 ways
Call some method of your Fragment in onPostExecute()
Use BroadcastReceiver in onPostExecute()
use EventBus library for passing event to your Fragment.
One way would be to declare a listener interface and pass an instance of that interface (or perhaps a Runnable) into the AsyncTask's constructor.
In your fragment code:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
new CDealDataSent(new Runnable() {
#Override
public void run() {
// perform update UI code here
}
}).execute(m_DealListingURL);
...
}
In your AsyncTask code:
class CDealDataSent extends AsyncTask<String, Void, String> {
private final Runnable mOnPostExecuteRunnable;
CDealDataSent(Runnable onPostExecuteRunnable) {
mOnPostExecuteRunnable = onPostExecuteRunnable;
}
...
#Override
protected void onPostExecute(String result) {
...
if (mPostExecuteRunnable != null) {
mPostExecuteRunnable.run();
}
...
}
}
You could also use an anonymous subclass of AsyncTask from your fragment and override onPostExecute():
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
new CDealDataSent() {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result); // be sure to call super first to do normal processing
... // update your UI here
}
}.execute(m_DealListingURL);
...
}
Note that both of these solutions are prone to Activity/Fragment leakage if you are not careful, as the parent class of the Runnable/anonymous subclass is retained as an implicit reference. Be sure to cancel any outstanding AsyncTasks if the user backs out of your activity in onDestroy().
You might be able to mitigate any potential leakage issues via a static nested class, or maybe pass a Handler instance to the AsyncTask for it to send a message on when onPostExecute() has done its job. See What's the correct way to implement AsyncTask? static or non static nested class? for a discussion on this.

How to send Login Boolean value to server in android

I am developing an app in which a login screen is visible to user and what I have to send to server is mobilenumber,password and isfirst true to server when user logging in first time and when user logout and again login I have to send isFirst false to server ,How can I achieve this problem.
Note:- I dont have to check value from shared Preference, I have to send isFirst true or false on user login first time and second time,first time is true and second time false to server using Jsons.
public class CLoginScreen extends Fragment {
public static String s_szLoginUrl = "http://543.168.0.110:8080/ireward/rest/json/metallica/getLoginInJSON";
public static String s_szresult = " ";
public static String s_szMobileNumber, s_szPassword;
public static String s_szResponseMobile, s_szResponsePassword;
public View m_Main;
public EditText m_InputMobile, m_InputPassword;
public AppCompatButton m_LoginBtn, m_ChangePass, m_RegisterBtn;
public ProgressDialog m_PDialog;
public CJsonsResponse m_oJsonsResponse;
public boolean isFirstLogin;
public JSONObject m_oResponseobject;
public Snackbar m_SnackBar;
public LinearLayout m_MainLayout;
public CLoginSessionManagement m_oLoginSession;
public boolean isFirstTimeLogin = true;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
m_Main = inflater.inflate(R.layout.login_screen, container, false);
((AppCompatActivity) getActivity()).getSupportActionBar().hide();
m_oLoginSession = new CLoginSessionManagement(getActivity());
Toast.makeText(getActivity(), "User Login Status: " + m_oLoginSession.isLogin(), Toast.LENGTH_LONG).show();
init();
return m_Main;
}
public void init() {
m_MainLayout = (LinearLayout) m_Main.findViewById(R.id.mainLayout);
m_InputMobile = (EditText) m_Main.findViewById(R.id.input_mobile);
m_InputPassword = (EditText) m_Main.findViewById(R.id.input_password);
m_LoginBtn = (AppCompatButton) m_Main.findViewById(R.id.btn_Login);
m_ChangePass = (AppCompatButton) m_Main.findViewById(R.id.btn_ChangePass);
m_ChangePass.setBackgroundColor(Color.TRANSPARENT);
m_ChangePass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CChangePasswordScreen()).commit();
}
});
m_RegisterBtn = (AppCompatButton) m_Main.findViewById(R.id.btn_Register);
m_RegisterBtn.setBackgroundColor(Color.TRANSPARENT);
m_RegisterBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CRegistrationScreen()).commit();
}
});
m_LoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new LoginAttempt().execute();
}
});
}
private class LoginAttempt extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
m_PDialog = new ProgressDialog(getActivity());
m_PDialog.setMessage("Please wait while Logging...");
m_PDialog.setCancelable(false);
m_PDialog.show();
}
#Override
protected String doInBackground(String... params) {
getLoginDetails();// getting login details from editText...........
InputStream inputStream = null;
m_oJsonsResponse = new CJsonsResponse();
isFirstLogin = true;
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(s_szLoginUrl);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.put("agentCode", s_szMobileNumber);
jsonObject.put("pin", s_szPassword);
jsonObject.put("firstloginflag", m_oLoginSession.isLogin());
// 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"); ///not required
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
// 9. receive response as inputStream
inputStream = entity.getContent();
System.out.print("InputStream...." + inputStream.toString());
System.out.print("Response...." + httpResponse.toString());
StatusLine statusLine = httpResponse.getStatusLine();
System.out.print("statusLine......" + statusLine.toString());
////Log.d("resp_body", resp_body.toString());
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
// 10. convert inputstream to string
if (inputStream != null) {
s_szresult = m_oJsonsResponse.convertInputStreamToString(inputStream);
//String resp_body =
EntityUtils.toString(httpResponse.getEntity());
}
} else
s_szresult = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
System.out.println("s_szResult....." + s_szresult);
System.out.println("password......" + s_szPassword);
// 11. return s_szResult
return s_szresult;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
m_PDialog.dismiss();
try {
m_oResponseobject = new JSONObject(response);// getting response from server
new Thread() {// making child thread...
public void run() {
Looper.prepare();
try {
if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Transaction Successful")) {
m_oLoginSession.setLoginData(s_szResponseMobile, s_szResponsePassword);
getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.container, new CDealMainListing()).commit();
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Agentcode Can Not Be Empty")) {
m_SnackBar = Snackbar.make(m_MainLayout, "Please enter valid mobile number", Snackbar.LENGTH_SHORT);
m_SnackBar.show();
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Pin Can Not Be Empty")) {
m_SnackBar = Snackbar.make(m_MainLayout, "Please enter Password", Snackbar.LENGTH_SHORT);
m_SnackBar.show();
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Invalid PIN")) {
m_SnackBar = Snackbar.make(m_MainLayout, "Invalid Password", Snackbar.LENGTH_SHORT);
m_SnackBar.show();
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Blocked due to Wrong Attempts")) {
m_SnackBar = Snackbar.make(m_MainLayout, "You are bloacked", Snackbar.LENGTH_SHORT);
m_SnackBar.show();
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {
m_SnackBar = Snackbar.make(m_MainLayout, "Connection Lost", Snackbar.LENGTH_SHORT);
m_SnackBar.show();
} else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Subscriber/Agent Not Found")) {
m_SnackBar = Snackbar.make(m_MainLayout, "User not found ! Kindly Register", Snackbar.LENGTH_LONG);
m_SnackBar.show();
}
Looper.loop();
} catch (JSONException e) {
e.printStackTrace();
}
}
}.start();
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getLoginDetails() {
s_szMobileNumber = m_InputMobile.getText().toString();
s_szPassword = m_InputPassword.getText().toString();
}
}
}

JSON POST request for download image from server in android

I need to download image and set it in to imageview . for parsing i use JSON POST request and for this i use base64 . I got base64 type data for the image tag in to log but the problem is that how t separate the value of that image and convert it in to string and then display it in to list view ??is there any alternative way without using base64 to display image then please suggest us.
For parsing of data i use JSON parser with HttpPost .
Now how to get the value of image from response JSON format that i display above that the confusion ??
Thanks in advance ..
You can do like this.
Create folder in server. put images in that folder. get the URL of the image and insert in to db.
then get the JSON value of that url
add this method and pass that url to this method.
Bitmap bitmap;
void loadImage(String image_location) {
URL imageURL = null;
try {
imageURL = new URL(image_location);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection connection = (HttpURLConnection) imageURL
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);// Convert to
// bitmap
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
Try below code:
JSONObject res = jsonObj.getJSONObject("root");
JSONObject data = jsonObj.getJSONObject("data");
JSONArray imgs= jsonObj.getJSONArray ("images");
for(int i=0;i<imgs.length();i++){
JSONObject Ldetails = Ldtls.getJSONObject(i);
String img= Ldetails.getString("image");
byte[] decodedString = Base64.decode(img,Base64.NO_WRAP);
InputStream inputStream = new ByteArrayInputStream(decodedString);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imagevw.setImageBitmap(bitmap);
}
where imagevw is your ImageView.
Use a Gson Parser and then parse the base64 image string to a byte array and apply on the image.
Your model classes will be as follows:
public class JsonWrapper
{
private Root root ;
public Root getroot()
{
return this.root;
}
public void setroot(Root root)
{
this.root = root;
}
}
public class Root
{
private Response response ;
public Response getresponse()
{
return this.response;
}
public void setresponse(Response response)
{
this.response = response;
}
}
public class Response
{
private Message message ;
public Message getmessage()
{
return this.message;
}
public void setmessage(Message message)
{
this.message = message;
}
private Data data ;
public Data getdata()
{
return this.data;
}
public void setdata(Data data)
{
this.data = data;
}
}
public class Message
{
private String type ;
public String gettype()
{
return this.type;
}
public void settype(String type)
{
this.type = type;
}
private String message ;
public String getmessage()
{
return this.message;
}
public void setmessage(String message)
{
this.message = message;
}
}
import java.util.ArrayList;
public class Data
{
private ArrayList<Image> images ;
public ArrayList<Image> getimages()
{
return this.images;
}
public void setimages(ArrayList<Image> images)
{
this.images = images;
}
private String last_synchronized_date ;
public String getlast_synchronized_date()
{
return this.last_synchronized_date;
}
public void setlast_synchronized_date(String last_synchronized_date)
{
this.last_synchronized_date = last_synchronized_date;
}
}
public class Image
{
private String web_id ;
public String getweb_id()
{
return this.web_id;
}
public void setweb_id(String web_id)
{
this.web_id = web_id;
}
private String blob_image ;
public String getblob_image()
{
return this.blob_image;
}
public void setblob_image(String blob_image)
{
this.blob_image = blob_image;
}
}
Once you have the json parse using Gson as follows:
JsonWrapper jsonWrapper = new JsonWrapper();
Gson gsonParser = new Gson();
jsonWrapper = gsonParser.fromJson(data, jsonWrapper.getClass());
Next you can iterate through all the images
ArrayList<Image> images = jsoinWrapper.getRoot().getResponse().getData().getImages();
for(Image image : images)
{
byte[] decodedString = Base64.decode(image.getblob_image(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
if (decodedString != null) {
imageViewtype.setImageBitmap(decodedByte);
}
}
public class SingleContactActivity extends Activity implements OnClickListener {
private static final String TAG_ImageList = "CatList";
private static final String TAG_ImageID = "ID";
private static final String TAG_ImageUrl = "Name";
private static String url_MultiImage;
TextView uid, pid;
JSONArray contacts = null;
private ProgressDialog pDialog;
String details;
// String imagepath = "http://test2.sonasys.net/Content/WallPost/b3.jpg";
String imagepath = "";
String imagepath2;
Bitmap bitmap;
ImageView image;
SessionManager session;
TextView myprofileId;
TextView pending;
TextView Categories, visibleTo;
int count = 0;
ImageButton btn;
// -----------------------
ArrayList<HashMap<String, String>> ImageList;
JSONArray JsonArray = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
url_MultiImage = "http://test2.sonasys.net/Android/GetpostImg?UserID=1&PostId=80";
new MultiImagePath().execute();
ImageList = new ArrayList<HashMap<String, String>>();
}
private class MultiImagePath extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url_MultiImage,
ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JsonArray = jsonObj.getJSONArray(TAG_ImageList);
if (JsonArray.length() != 0) {
for (int i = 0; i < JsonArray.length(); i++) {
JSONObject c = JsonArray.getJSONObject(i);
String Img_ID = c.getString(TAG_ImageID);
String Img_Url = c.getString(TAG_ImageUrl);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ImageID, Img_ID);
contact.put(TAG_ImageUrl, Img_Url);
// adding contact to contact list
ImageList.add(contact);
}
}
Log.e("JsonLength", "length is ZERO");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
AutoGenImgBtn();
}
}
#SuppressWarnings("deprecation")
public void AutoGenImgBtn() {
int count = ImageList.size();
LinearLayout llimage = (LinearLayout) findViewById(R.id.llimage);
ImageButton[] btn = new ImageButton[count];
for (int i = 0; i < count; i++) {
btn[i] = new ImageButton(this);
btn[i].setId(Integer.parseInt(ImageList.get(i).get(TAG_ImageID)));
btn[i].setOnClickListener(this);
btn[i].setTag("" + ImageList.get(i).get(TAG_ImageUrl));
btn[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
btn[i].setImageDrawable(getResources().getDrawable(drawable.di1));
btn[i].setAdjustViewBounds(true);
// btn[i].setTextColor(getResources().getColor(color.white));
llimage.addView(btn[i]);
}
}
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
btn = (ImageButton) v;
String s = btn.getTag().toString();
new ImageDownloader().execute(s);
}
private class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... param) {
// TODO Auto-generated method stub
return downloadBitmap(param[0]);
}
#Override
protected void onPreExecute() {
Log.i("Async-Example", "onPreExecute Called");
pDialog = new ProgressDialog(SingleContactActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.setTitle("In progress...");
// pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setIcon(android.R.drawable.stat_sys_download);
pDialog.setMax(100);
// pDialog.setTitle("Post Details");
pDialog.show();
}
#Override
protected void onPostExecute(Bitmap result) {
Log.i("Async-Example", "onPostExecute Called");
if (bitmap != null) {
btn.setImageBitmap(bitmap);
}
if (pDialog.isShowing())
pDialog.dismiss();
}
private Bitmap downloadBitmap(String url) {
// initilize the default HTTP client object
final DefaultHttpClient client = new DefaultHttpClient();
// forming a HttoGet request
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
// check 200 OK for success
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode
+ " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
// getting contents from the stream
inputStream = entity.getContent();
// decoding stream data back into image Bitmap that
// android understands
bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// You Could provide a more explicit error message for
// IOException
getRequest.abort();
Log.e("ImageDownloader", "Something went wrong while"
+ " retrieving bitmap from " + url + e.toString());
}
return null;
}
}
# Add Service Handler Class#
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
*
* */
public String makeServiceCall(String url, int method,List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}

Android GSON processing remote JSON runtime exception

I am attempting to write an Android app which casts JSON input. This is my sample input.
I have the following class to serve as the data container:
public class DATA {
public Long id;
public String title;
public String author;
public String url;
public String date;
public String body;
public DATA() {
// TODO Auto-generated constructor stub
}
#Override
public String toString(){
return "DATA-Oblect: ID=> " + id + "/nTITLE=> " + title;
}
}
Using the following code:
protected void doInBackground(String... url) {
try{
//create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://kylewbanks.com/rest/posts");//url[0]);
//perform the request and check the status code
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200){
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
content = entity.getContent();
try{
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
List<DATA> Data = new ArrayList<DATA>();
Data = Arrays.asList(gson.fromJson(reader, DATA[].class));
content.close();
}catch(Exception ex){
Log.e(TAG, "JSON parse failed due to: " + ex);
}
}else{
Log.e(TAG, "Server response code: " + statusLine.getStatusCode());
}
}catch(Exception ex){
Log.e(TAG, "HTTP-Post failed due to: " + ex);
}
}
I get the following exception error:
JSON parse failed due to: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
What am I doing wrong?
Update
The following the the my main activity code:
public class MainActivity extends Activity {
private List<DATA> Data;
public static final String jsonSource = "http://kylewbanks.com/rest/posts";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
// DataRetriever("http://kylewbanks.com/rest/posts");
new DataRetriever(this.getApplicationContext()).execute(jsonSource);
}
/**
* Callback function for handling retrieved data from the
* DATARetrieve class
* #param Data
*/
public void DataListDrop(List<DATA> Data){
this.Data = Data;
Toast.makeText(MainActivity.this, "Testing ... testing!", Toast.LENGTH_SHORT).show();
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
for(DATA data : MainActivity.this.Data){
Toast.makeText(MainActivity.this, data.title, Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Callback function for responding no-data return from the
* DATARetrieve class
*/
private void NoData(){
runOnUiThread(new Runnable() {
#Override
public void run(){
Toast.makeText(MainActivity.this, "No data to process! Checkout LogCat.", Toast.LENGTH_SHORT).show();
}
});
}
}

Categories

Resources