Android GSON processing remote JSON runtime exception - android

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

Related

How to dismiss progress bar once otp read from Inbox in 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.

Access Http response string in the Activity

I have a method name Request() in the onCreate method of the activity.
private void Request() {
new PostDataAsyncTask(textEmail, tValue).execute();
}
Iam passing two strings in it and the async class is as follows:
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
GameActivity game= new GameActivity();
private String data,data1;
public PostDataAsyncTask(String textEmail, String hello) {
data = textEmail;
data1= hello;
}
long date = System.currentTimeMillis();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM MM dd, yyyy h:mm a");
String dateString = simpleDateFormat.format(Long.valueOf(date));
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
try {
postText();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String lenghtOfFile) {
}
private void postText(){
try{
String postReceiverUrl = "http://techcube.pk/game/game.php";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(postReceiverUrl);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email", data));
nameValuePairs.add(new BasicNameValuePair("score", data1));
nameValuePairs.add(new BasicNameValuePair("datetime", dateString));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
Log.v("SuccesS", "Response: " + responseStr);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Now what i want is that i want to get the value of responseStr in my MainActivity that is generated when posttext method called.
How to show this responseStr value in the MainActivity?
Remember there is a new class that i made named as PostDataAsyncTask so how to access responseStr from this class and show it in my mainActivity as a Toast or Textview?
Please Help
You can create an interface that you pass into the method in question. For example
public interface INetworkResponse {
void onResponse(String response);
void onError(Exception e);
}
You would then need to create a concrete implementation of the interface. perhaps as a child class inside the activity that calls the AsyncTask.
public class MyActivity extends Activity {
private void Request() {
NetworkResponse response = new NetworkResponse();
new PostDataAsyncTask(textEmail, tValue, response).execute();
}
public class NetworkResponse implements INetworkResponse {
public void onResponse(String response) {
// here is where you would process the response.
}
public void onError(Exception e) {
}
}
}
Then change the async task constructor to include the new interface.
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
GameActivity game= new GameActivity();
private String data,data1;
private INetworkResponse myResponse;
public PostDataAsyncTask(String textEmail, String hello, INetworkResponse response) {
data = textEmail;
data1 = hello;
myResponse = response
}
private void postText() {
// do some work
myResponse.onResponse(myResultString);
}
}
You can create a Handler as an Inner class inside your Activity to send data between your thread and UIthread:
public class YourHandler extends Handler {
public YourHandler() {
super();
}
public synchronized void handleMessage(Message msg) {
String data = (String)msg.obj;
//Manage the data
}
}
Pass this object in the header of PostDataAsyncTask
public PostDataAsyncTask(String textEmail, String hello, YourHandler mYourHandler) {
data = textEmail;
data1= hello;
this.mYourHandler = mYourHandler;
}
and send the data in postText() to the Activity:
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
msg = Message.obtain();
msg.obj = responseStr;
mYourHandler.sendMessage(msg);
Log.v("SuccesS", "Response: " + responseStr);
}

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();

I have used Gson libary,but can see my output

This is my Main Class.Can any one tell me why it s returning null in System.print().I have used Gson external libs.What i am doing wrong here.How can i display all contains
public class PostsActivity extends Activity {
private static final String TAG = "PostsActivity";
private List<Post> posts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts);
PostFetcher fetcher = new PostFetcher();
fetcher.execute();
}
private void handlePostsList(List<Post> posts) {
this.posts = posts;
runOnUiThread(new Runnable() {
#Override
public void run() {
for(Post post : PostsActivity.this.posts) {
Toast.makeText(PostsActivity.this, post.TITLE, Toast.LENGTH_SHORT).show();
}
}
});
}
private void failedLoadingPosts() {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(PostsActivity.this, "Failed to load Posts. Have a look at LogCat.", Toast.LENGTH_SHORT).show();
}
});
}
private class PostFetcher extends AsyncTask<Void, Void, String> {
private static final String TAG = "PostFetcher";
public static final String SERVER_URL = "http://indianpoliticalleadersmap.com/android/DemoSchool/json/json_item.php";
#Override
protected String doInBackground(Void... params) {
try {
//Create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(SERVER_URL);
//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();
try {
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("M/d/yy hh:mm a");
Gson gson = gsonBuilder.create();
Post po = gson.fromJson(reader, Post.class);
List<Post> posts = Arrays.asList(po);
System.out.println("ID:"+po);
content.close();
handlePostsList(posts);
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
failedLoadingPosts();
}
} else {
Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
failedLoadingPosts();
}
} catch(Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
failedLoadingPosts();
}
return null;
}
}
}
//Post.java
public class Post {
#SerializedName("id")
public long ID;
public String TITLE;
public String AUTHOR;
public String URL;
#SerializedName("date")
public Date dateCreated;
public String body;
public List<Tag> tags;
public Post() {
}
public String toString() {
return "Student [id=" + ID + ", title="
+ TITLE + ", thumb_url=" + URL
+ ", dt=" + AUTHOR + "]";
}
}
There are a few things you need to consider. First of all, your fields need have proper #SerializedName("") annotation. It indicates that the property name (like thumb_url, dt) does not match the field name in your JSON. If both names do match, there is no need for the annotation.
Secondly, you need to "parse" the response that you get from the server to JsonObject and then read the JsonElement.
Here's the code you need:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("yy-d-M hh:mm");
//2014-06-14 02:39:24
//yy-d-M hh:mm
Gson gson = gsonBuilder.create();
List<Post> posts = new ArrayList<Post>();
JsonParser jsonParser = new JsonParser();
JsonObject details = jsonParser.parse(reader).getAsJsonObject();
JsonArray array = details.getAsJsonArray("veg_food");
for ( JsonElement element : array ){
Post post = gson.fromJson(element, Post.class);
posts.add(post);
}
System.out.println("ID:"+ posts);
Also, make sure you change your Post.java class to this:
#SerializedName("id")
public long ID;
#SerializedName("title")
public String TITLE;
#SerializedName("thumb_url")
public String URL;
#SerializedName("dt")
public Date dateCreated;
Hope it helps.
[EDIT]
Output:

Properly Using AsyncTask get()

I am running into a problem. I need to use asynctask to retrieve JSON data and I need that data before I moved to the next part of the program. However, when using the get() method of AsyncTask I have 5 to 8 sec black screen before I see the data is displayed. I would like to display a progress dialog during the data retrieval but I cannot do this due to the black screen. Is there a way to put into another thread? here is some code
AsyncTask
public class DataResponse extends AsyncTask<String, Integer, Data> {
AdverData delegate;
Data datas= new Data();
Reader reader;
Context myContext;
ProgressDialog dialog;
String temp1;
public DataResponse(Context appcontext) {
myContext=appcontext;
}
#Override
protected void onPreExecute()
{
dialog= new ProgressDialog(myContext);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.setMessage("Retrieving...");
dialog.show();
};
#Override
protected Data doInBackground(String... params) {
temp1=params[0];
try
{
InputStream source = retrieveStream(temp1);
reader = new InputStreamReader(source);
}
catch (Exception e)
{
e.printStackTrace();
}
Gson gson= new Gson();
datas= gson.fromJson(reader, Data.class);
return datas;
}
#Override
protected void onPostExecute(Data data)
{
if(dialog.isShowing())
{
dialog.dismiss();
}
}
private InputStream retrieveStream(String url) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(url);
try {
HttpResponse getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(),
"Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
}
catch (IOException e) {
getRequest.abort();
Log.w(getClass().getSimpleName(), "Error for URL " + url, e);
}
return null;
}
}
DisplayInfo
public class DisplayInfo extends Activity implements AdverData {
public static Data data;
public ProjectedData attup;
public ProjectedData attdown;
public ProjectedData sprintup;
public ProjectedData sprintdown;
public ProjectedData verizionup;
public ProjectedData veriziondown;
public ProjectedData tmobileup;
public ProjectedData tmobiledown;
public ProjectedAll transfer;
private ProgressDialog dialog;
public DataResponse dataR;
Intent myIntent; // gets the previously created intent
double x; // will return "x"
double y; // will return "y"
int spatial; // will return "spatial"
//public static Context appContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
dialog= new ProgressDialog(DisplayInfo.this);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.setMessage("Retrieving...");
dialog.show();
myIntent= getIntent(); // gets the previously created intent
x = myIntent.getDoubleExtra("x",0); // will return "x"
y = myIntent.getDoubleExtra("y", 0); // will return "y"
spatial= myIntent.getIntExtra("spatial", 0); // will return "spatial"
String URL = "Some URL"
dataR=new DataResponse().execute(attUp).get();
#Override
public void onStart()
{more code}
When you are using get, using Async Task doesn't make any sense. Because get() will block the UI Thread, Thats why are facing 3 to 5 secs of blank screen as you have mentioned above.
Don't use get() instead use AsyncTask with Call Back check this AsyncTask with callback interface

Categories

Resources