how read a Json file From a URL? - java

I wrote a program
I want download a json file from a URL and show it in a text view ..
When you click the button the program will stop after a few seconds .
I do not know what the problem is .
Please help me..
java code:
public class MainActivity extends Activity {
TextView tx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b=(Button)findViewById(R.id.button2);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new GetJsonTask().execute("http://shahid.ifilmtv.ir/query/englishcurrentshows");
}
});
}
public class GetJsonTask extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... urls) {
// TODO Auto-generated method stub
return getJson(urls[0]);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
JSONArray jsonArray;
try {
jsonArray = new JSONArray(result);
JSONObject object = jsonArray.getJSONObject(1);
tx.setText(object.getString("id"));
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public String getJson(String url) {
try {
InputStream inputStream = null;
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = defaultHttpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
inputStream.close();
String result = sb.toString();
return result;
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "ERROR : " + ex, Toast.LENGTH_LONG).show();
return null;
}
}
}

I think the issue is in getJSON method. I have rewritten a following code. Please try this.
public String getJson(String url) {
try {
DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
ResponseHandler responseHandler = new BasicResponseHandler();
Object resp = defaultHttpClient.execute(httpPost, responseHandler);
String json = resp.toString();
// create a object here if you want
JSONObject obj = new JSONObject(json);
return json;
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "ERROR : " + ex, Toast.LENGTH_LONG).show();
return null;
}
}

Related

I got error Android JSON parsing Retrieve from URL

I new to Android... I am trying Android JSON parsing Retrieve from URL and set MySQL DB data into TextView but I got an error. I tried many solutions but it's not working Help me to solve this error
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String org.json.JSONObject.getString(java.lang.String)' on
a null object reference at
com.example.testapplication.MainActivity$GetDataFromServerIntoTextView.onPostExecute(MainActivity.java:123)at
com.example.testapplication.MainActivity$GetDataFromServerIntoTextView.onPostExecute(MainActivity.java:63)
Error shows this line textView.setText(jsonObject.getString("distance"));
My Code
HttpResponse httpResponse;
Button button;
TextView textView;
static JSONObject jsonObject = null ;
String StringHolder = "" ;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
textView = (TextView)findViewById(R.id.textView);
progressBar = (ProgressBar)findViewById(R.id.progressBar);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progressBar.setVisibility(View.VISIBLE);
new GetDataFromServerIntoTextView(MainActivity.this).execute();
}
});
}
public class GetDataFromServerIntoTextView extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetDataFromServerIntoTextView(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpClient httpClient = new DefaultHttpClient();
String HttpURL = "https://api.myjson.com/bins/1cuzhn";
// Adding HttpURL to my HttpPost oject.
HttpPost httpPost = new HttpPost(HttpURL);
try {
httpResponse = httpClient.execute(httpPost);
StringHolder = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONArray jsonArray = new JSONArray(StringHolder);
jsonObject = jsonArray.getJSONObject(0);
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
try {
textView.setText(jsonObject.getString("distance"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
progressBar.setVisibility(View.GONE);
}
}
I modified your AsyncTask and tested below code and its working fine. Let me know if you found any issue.
Add below dependencies
// OKHTTP
implementation 'com.squareup.okhttp:okhttp:2.5.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
implementation 'org.apache.httpcomponents:httpcore:4.4.10'
and
public class GetDataFromServerIntoTextView extends AsyncTask<Void, Void,String>
{
public Context context;
public GetDataFromServerIntoTextView(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... voids) {
String strUrl = "https://api.myjson.com/bins/1cuzhn";
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d(TAG, "Exception while downloading url " + e.toString());
} finally {
try {
iStream.close();
} catch (IOException e) {
e.printStackTrace();
}
urlConnection.disconnect();
}
return data;
}
#Override
protected void onPostExecute(String data) {
super.onPostExecute(data);
try {
if (data != null) {
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Here is your all data of distance and time
Log.e(TAG, "distance " + jsonObject.get("distance"));
Log.e(TAG, "time " + jsonObject.get("time"));
}
} else {
Log.e(TAG, "onPostExecute: null json object");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
You are using POST request where as your api is expecting GET request
Here is more details about GET and POST
HttpPost httpPost = new HttpPost(HttpURL);
replace this with following
HttpGet request = new HttpGet(HttpURL);
To avoid crash replace your code with
textView.setText(jsonObject.getString("distance"));
this
textView.setText(jsonObject.isNull("distance") ? "null object" : jsonObject.getString("distance"));

How to handle Login Successful in json? [duplicate]

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
I am trying to implement login and signup form in Android with the help of JSON using post method. When i signup and enter the details it successfully register and data has been shown in my local host sever and when i login its enter wrong username and password its show incorrect details in toast and enter right details shows login success in toast, but i want when i enter right details its goes to another activity. and enter wrong details shows only toast. Here is the code :-
MainActivity.java
public class MainActivity extends Activity {
public static HashMap<Sound, MediaPlayer> SOUND_MAP=
new HashMap<Sound, MediaPlayer>();
public static int userScore= 0, computerScore=0,
buddyBoxId = 1, computerBoxId = 1;
public static Context CTX;
Button play;
private static final String TAG = "LoginActivity";
String URL = "http://10.0.2.2/test_android/index.php";
JSONParser jsonParser=new JSONParser();
ProgressDialog progressDialog;
TextView register_caption;
AdView adView = null;
private AdView mAdView;
EditText username, password;
Button btnSignIn, btnRegister;
ImageView fb;
int i=0;
private AdRequest adRequest;
InterstitialAd mInterstitialAd;
static MediaPlayer media;
static Handler mediaHandler;
public static int stat=0, totTurn = 0, maxEnd = 100;
public static SharedPreferences configs;
public static SharedPreferences.Editor configuration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = (EditText) findViewById(R.id.email);
password = (EditText)findViewById(R.id.passwordd);
btnSignIn = (Button) findViewById(R.id.play);
register_caption = (TextView) findViewById(R.id.register_caption);
fb = (ImageButton) findViewById(R.id.btnfb);
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AttemptLogin attemptLogin = new AttemptLogin();
attemptLogin.execute(username.getText().toString(), password.getText().toString(), "");
}
});
register_caption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(MainActivity.this,Registration.class);
startActivity(in);
}
});
CTX = getApplicationContext();
configs = CTX. getSharedPreferences("snake_n_ladder", 0);
configuration = configs.edit();
loadConfig();
loadMedia();
}
private class AttemptLogin extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... args) {
String email = args[2];
String password = args[1];
String name = args[0];
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", name));
params.add(new BasicNameValuePair("password", password));
if (email.length() > 0)
params.add(new BasicNameValuePair("email", email));
JSONObject json = jsonParser.makeHttpRequest(URL, "POST", params);
return json;
}
protected void onPostExecute(JSONObject result) {
// dismiss the dialog once product deleted
//Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
try {
if (result != null) {
Toast.makeText(getApplicationContext(), result.getString("message"), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unable to retrieve any data from server", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
JsonParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static JSONArray jArr = null;
static String json = "";
static String error = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
ArrayList<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method.equals("POST")){
// request method is POST
// defaultHttpClient
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
try {
Log.e("API123", " " +convertStreamToString(httpPost.getEntity().getContent()));
Log.e("API123",httpPost.getURI().toString());
} catch (Exception e) {
e.printStackTrace();
}
HttpResponse httpResponse = httpClient.execute(httpPost);
Log.e("API123",""+httpResponse.getStatusLine().getStatusCode());
error= String.valueOf(httpResponse.getStatusLine().getStatusCode());
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method.equals("GET")){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.d("API123",json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
jObj.put("error_code",error);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
private String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
return sb.toString();
}
}
protected void onPostExecute(JSONObject result) {
try {
if (result != null)
{
if(result.getString("message").equals("Successfully logged in"))
{
Intent intent = new Intent(ThisActivity.this,NewActivity.class);
startActivity(intent);
finish();
}
else
{
Toast.makeText(this,"Invalid credentials",Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "Unable to retrieve any data from
server", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}

Use XML parser for rss XML text file which is store in Edit Text field

I want to read XML file which is store in editTextxml.setText(xml).
In that rss xml tags are there and i want to use XML parser to display this tags.
view-source:http://syndication.indianexpress.com/rss/latest-news.xml
public class XmlDownloader extends Activity {
LoginDataBaseAdapter loginDataBaseAdapter;
InputStream in;
String xml;// = onGet
// ("http://syndication.indianexpress.com/rss/latest-news.xml");
Button downloadxml;
Button parsingXML;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.xmldownloader);
downloadxml = (Button) findViewById(R.id.downloadxml);
final EditText editTextxml = (EditText) findViewById(R.id.editTextXml);
parsingXML = (Button) findViewById(R.id.ParsingXMLData);
downloadxml.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
onGet("http://syndication.indianexpress.com/rss/latest-news.xml");
Log.d("test", xml);
editTextxml.setText(xml);
}
});
}
private String onGet(String url) {
// TODO Auto-generated method stub
/* String result = null; */
HttpResponse response;
HttpEntity entity;
try {
HttpPost httppost = new HttpPost(url);
DefaultHttpClient httpClient = new DefaultHttpClient();
response = httpClient.execute(httppost);
entity = response.getEntity();
if (entity != null) {
InputStream is = entity.getContent();
if (is != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"), 8 * 1024);
while ((line = reader.readLine()) != null) {
sb.append(line); // .append("\n");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
is.close();
}
xml = sb.toString();
}
entity.consumeContent();
}
httpClient.getConnectionManager().shutdown();
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return xml;
}
I want to use editTextxml.setText(xml) to get XML parsing in another Button
What is the XML parsing for this code

Why is the Progess Dialog appearing when back button is pressed?

When I go back to the previous activity by pressing the back button the progress dialog is appearing and not disappearing. When I minimize they the app the progress dialog disappears.
Here is the code for the async class
public class BackGroundTask extends AsyncTask<String, String, JSONObject> {
List<NameValuePair> postparams = new ArrayList<NameValuePair>();
private ProgressDialog pd;
String url = null;
String method = null;
Context context;
public BackGroundTask(String url, String method,
List<NameValuePair> params, Context context) {
this.url = url;
postparams = params;
this.method = method;
this.context = context;
//pd = new ProgressDialog(context);
//pd.setTitle("Processing...");
//pd.setMessage("Please wait.");
//pd.setCancelable(false);
//pd.setIndeterminate(true);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(context);
pd = ProgressDialog.show(context, "Processing...", "Please wait.", true, false);
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
pd.dismiss();
}
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
// Making HTTP request
try {
// Making HTTP request
// check for request method
if (method.equals("POST")) {
// request method is POST
// defaultHttpClient
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(postparams));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
HttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(postparams,
"utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
System.out.println(json);
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
//pd.dismiss();
// return JSON String
return jObj;
}
}
You aren't dismissing it when you finish the Activity and the task must not be done. Override finish() and dismiss it if needed
#Override
public void finish()
{
if (pd.isShowing()
{
pd.dismiss();
}
super.finish();
}
You could also Override onBackPressed() and put this code there but since pressing the back button calls finish() its probably safer just to do it there.
Also, you are comparing Strings correctly in one place
if (method.equals("POST")) // correct
but not others
else if (method == "GET") // incorrect

how send request from android form to localhost URL???

i want to send android form data to specific URL (like login.php page "this is a page of my website that will verification of form data from DB saved record")
See this tutorial and you are done
http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
You actually need two Classes to do this
1. Your Activity
2. JSON Parser
Here is the sample code for two of them, you can modify it as per your own needs
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
static JSONArray jArr = null;
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
Log.i("PHP Error", "["+json+"]");
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.getMessage() + json);
}
// return JSON String
return jObj;
}
public JSONArray getAllMessages(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
Log.i("PHP Error", "["+json+"]");
// try parse the string to a JSON object
try {
jArr = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.getMessage() + json);
}
// return JSON String
return jArr;
}
}
Activity
public class Home extends Activity {
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
String message;
private static String url_addmessage = "http://www.yourdomain.com/addmessage.php";
private static final String TAG_SUCCESS = "success";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
final EditText et = (EditText)findViewById(R.id.editText1);
Button b1 = (Button)findViewById(R.id.button1);
Button b2 = (Button)findViewById(R.id.button2);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try{
message = et.getText().toString();
Log.i("message to be posted", message);
new RegisterMe().execute();
}catch(Exception e){
Log.e("Exception while getting Message", e.getMessage().toString());
}
}
});
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(Home.this, GetMessage.class));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_home, menu);
return true;
}
class RegisterMe extends AsyncTask<String, String, String>{
String Message=null;
public boolean workdone(String Message){
boolean x=false;
if(Message == "Done"){
x=true;
}
return x;
}
#Override
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(Home.this);
pDialog.setMessage("Transaction In Progress... \n You Have The Right To Remain \n Silent & Patient :)");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("message", message));
JSONObject json = jsonParser.makeHttpRequest(url_addmessage, "GET", params);
Log.d("Create Response", json.toString());
try{
int success = json.getInt(TAG_SUCCESS);
if(success == 1){
Message = "Done";
Log.d("Work Done", "Message Added");
}
else{
Log.d("Work Done", "Message Not Added");
}
} catch(JSONException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url){
pDialog.dismiss();
if(new RegisterMe().workdone(Message)){
Toast.makeText(Home.this, "Message Added Successfully.",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(Home.this, "Sorry There was some error in processing your request, please try after some time.",Toast.LENGTH_LONG).show();
}
}
}
}

Categories

Resources