this is my class that receive data from server: it does not show notification
but if i take sendBroadcast(intent) and Intent out of try and catch blocks and make msg=null; it show notification but with empty message
please i need your help.
package com.example.hussienalrubaye.myapplication;
import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Sev_data extends IntentService {
public static boolean ServiceIsRun = false;
public Sev_data() {
super("MyWebRequestService");
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
while (ServiceIsRun) {
int id_s=0;//هنا رقم اخر رسلة وصلة التطبيق
String url0 = "http://localhost/sendapp.php?co>"+id_s;//رايط ملف الداتة من السيرفر
String msg;
try {
URL url = new URL(url0);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
msg = Stream2String(in);
in.close();
JSONObject jsonRootObject = new JSONObject(msg);
JSONArray jsonArray = jsonRootObject.optJSONArray("date");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id= jsonObject.optString("id");
String title = jsonObject.optString("title");
String mess = jsonObject.optString("description");
///// هنا نهاية الموضوع دي اخر رسلة علي السيرفر
}
// creat new intent
intent = new Intent();
//set the action that will receive our broadcast
intent.setAction("com.example.Broadcast");
// add data to the bundle
intent.putExtra("msg", msg);
// send the data to broadcast
sendBroadcast(intent);
//delay for 50000ms
} catch (Exception e) {
}
try{
Thread.sleep(20000);
}catch (Exception ex){}
}
}
String date="";
public String Stream2String(InputStream inputStream) {
BufferedReader bureader=new BufferedReader( new InputStreamReader(inputStream));
String line ;
String Text="";
try{
while((line=bureader.readLine())!=null) {
Text+=line;
}
inputStream.close();
}catch (Exception ex){}
return Text;
}
}
and this is receiver class:
package com.example.doblist.mydobservice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// get the bundles in the message
final Bundle bundle = intent.getExtras();
// check the action equal to the action we fire in broadcast,
if ( intent.getAction().equalsIgnoreCase("com.example.Broadcast"))
//read the data from the intent
{ NewMessageNotification notfilyme= new NewMessageNotification();
notfilyme.notify(context,bundle.getString("msg"),223);}
// Toast.makeText(context,bundle.getString("msg"),Toast.LENGTH_LONG).show();
}
}
i add all AndroidManifest permission all things well but it dose not show notification
I want to know. is the cod that get data from server true or not
Related
im working on this program ,which i have an Android app that uses Nodejs server.the host is -https://rocky-thicket-82184.herokuapp.com.
now, im trying to just send and recieve a post request . but it seems to not
work.
in the server side i get an error like : cannot GET/.
and in the client side i get :error exeption https://rocky-thicket-82184.herokuapp.com.
I cannot find the problem ,i feel like i'm missing something ...
here is my Android mainActivity.java:
package com.example.shanijoffe.hungry_monkey;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.JsonReader;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.os.AsyncTask;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.stormpath.sdk.Stormpath;
import com.stormpath.sdk.StormpathConfiguration;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.NameValuePair;
import cz.msebera.android.httpclient.client.ClientProtocolException;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.entity.UrlEncodedFormEntity;
import cz.msebera.android.httpclient.client.methods.HttpPost;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
import cz.msebera.android.httpclient.message.BasicNameValuePair;
import static com.loopj.android.http.AsyncHttpClient.log;
public class MainActivity extends AppCompatActivity
{
EditText user_name_edit;
EditText password_edit;
Button loginButton;
String user;
String user_pass;
private static final String TAG = "MyActivity";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
user_name_edit=(EditText)findViewById(R.id.txt_usrname);
password_edit=(EditText)findViewById(R.id.txt_password);
loginButton=(Button)findViewById(R.id.btn_login);
Log.i(TAG,"before connection");
}
public void OnClick(final View view) {
view.setEnabled(false);
user=user_name_edit.getText().toString();
user_pass=password_edit.getText().toString();
new SendPostRequest().execute();
//
//
}
public class SendPostRequest extends AsyncTask<String, Void, String>
{
String user_name=user_name_edit.getText().toString();
String user_pass=password_edit.getText().toString();
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try {
Log.e("MainActivity", "in SendPostRequest ");
URL url = new URL("https://rocky-thicket-82184.herokuapp.com");
InputStream inp = (InputStream) url.getContent();
Log.e("stream",inp.toString());
JSONObject postDataParams = new JSONObject();
postDataParams.put("username", user);
postDataParams.put("password", user_pass);
Log.e("params", postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
int responseCode;
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"))) {
String encoded_string = getPostDataString(postDataParams);
Log.e("encoded", encoded_string);
//writer.write(getPostDataString(postDataParams));
writer.write(postDataParams.toString());
writer.flush();
writer.close();
}
os.close();
responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
Log.i("MainActivty",sb.toString());
return sb.toString();
} else {
return new String("false : " + responseCode);
}
}
catch (Exception e)
{
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_LONG).show();
}
public String getPostDataString(JSONObject params) throws Exception
{
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
}
}
and here is the nodejs code:
var express=require('express');
var bodyParser=require('body-parser');
var app=express();
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.get('/',function(req,res){
res.sendFile(__dirname + '/index.html');
});
app.post('/',function(req,res){
console.log(req.body);
if (!req.body)
return res.sendStatus(400)
res.send('welcome, ' + req.body.user)
});
app.listen(process.env.PORT || 3000)
can anyone take a look and see if they can help ?
Thanks alot :)
As title suggests, here is the format of the JSON:
http://prntscr.com/elb4fz. Now I'm not sure if I have the parse method working properly as I think that SearchResults is the array and it'll show each individual result as an object.
I have my networkutils code as such:
package companionsdirect.practice;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Albedo on 3/17/2017.
*/
public class NetworkingUtil {
private static final String TAG = "NetworkUtils";
List<Product> items = new ArrayList<>();
public byte[] getUrlBytes(String urlSpec) throws IOException {
URL url = new URL(urlSpec);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
InputStream in = connection.getInputStream();
if(connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException(connection.getResponseMessage() +
": with " + urlSpec);
}
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = in.read(buffer)) > 0) {
out.write(buffer, 0, bytesRead);
}
out.close();
return out.toByteArray();
} finally {
connection.disconnect();
}
}
public String getUrlString(String urlSpec) throws IOException {
return new String(getUrlBytes(urlSpec));
}
public List<Product> fetchItems(String url) {
try {
String jsonString = getUrlString(url);
Log.i(TAG, "Received JSON: " + jsonString);
JSONObject jsonBody = new JSONObject(jsonString);
parseItems(items, jsonBody);
} catch (IOException ioe) {
Log.i(TAG, "Failed to fetch items", ioe);
} catch (JSONException je) {
Log.e(TAG, "Failed to parse JSON", je);
}
return items;
}
public List<Product> getProdList() {
return items;
}
private void parseItems(List<Product> items, JSONObject jsonBody) throws IOException, JSONException {
//JSONObject reviewItem = jsonBody.getJSONObject();
JSONArray reviewArray = jsonBody.getJSONArray("SearchResults");
for(int i = 0;i<reviewArray.length();i++) {
JSONObject reviewItem = reviewArray.getJSONObject(i);
Product currentProductReview = new Product();
currentProductReview.setmSummary(reviewItem.getString("Summary"));
currentProductReview.setmTitle(reviewItem.getString("Title"));
currentProductReview.setmRecordType(reviewItem.getString("RecordType"));
items.add(currentProductReview);
}
}
}
And this is the activity with the asynctask:
package companionsdirect.practice;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class ReturnReviewsActivity extends AppCompatActivity {
public String builtURL;
List<Product> prodList;
private static final String TAG = "ReturnReviewsActivity";
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_return_reviews);
Intent intent = getIntent();
String url = intent.getStringExtra(MainActivity.EXTRA_MSG);
prodList = new ArrayList<Product>();
builtURL = url;
new FetchItemsTask().execute();
tv = (TextView) findViewById(R.id.tv);
for(Product x : prodList) {
tv.setText(x.getmTitle() + " " + x.getRating() + " \n");
}
}
private class FetchItemsTask extends AsyncTask<Void, Void, Void> {
private List<Product> list;
#Override
protected Void doInBackground(Void... params) {
NetworkingUtil productData = new NetworkingUtil();
list = productData.fetchItems(builtURL);
return null;
}
}
}
What gives? The log shows that the json is being received,but I try to set the textview to whatever is in the list and nothing shows.
Try this
tv = (TextView) findViewById(R.id.tv);
for(Product x : prodList) {
//append the text view
tv.append(x.getmTitle() + " " + x.getRating() + " \n");
}
I'm trying to do a PIN input as a dialog.
This part is working fine. But when I enter my pin and try to compare it to my requested pin it just closes my dialog.
So here is my code:
PinInput.java
package com.ts.techassi.ts;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class PinInput extends DialogFragment {
public final static String EXTRA_MESSAGE = "tuerschild.saschalautenschlaege.tuerschild.MESSAGE";
Context context;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.pin_input, null));
Log.i("LOL", "Started");
builder.setMessage("Enter PIN")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Uri url = readUrl();
Dialog f = (Dialog) dialog;
// String ts_id = url.getLastPathSegment();
EditText pin = (EditText)f.findViewById(R.id.pin);
TextView test = (TextView) f.findViewById(R.id.response);
String pinString = pin.getText().toString();
try {
String response = new Http().execute().get();
// Log.i("test", response);
if( response == pinString) {
Boolean isLauncher = isMyAppLauncherDefault();
if(isLauncher == true){
resetPreferredLauncherAndOpenChooser(context);
}
} else {
PinInput.this.getDialog().cancel();
}
} catch (Exception e) {
e.printStackTrace();
Log.i("Test",e.toString());
}
}
})
.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
return builder.create();
}
public Uri readUrl() {
String fileDirectory = Environment.getExternalStorageDirectory()+"/dbDoorsign/url.txt";
File file = new File(fileDirectory);
StringBuilder text = new StringBuilder();
;
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
}
br.close();
}
catch (IOException e) {
}
return Uri.parse(text.toString());
}
private boolean isMyAppLauncherDefault() {
final IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN);
filter.addCategory(Intent.CATEGORY_HOME);
List<IntentFilter> filters = new ArrayList<IntentFilter>();
filters.add(filter);
final String myPackageName = getActivity().getPackageName();
List<ComponentName> activities = new ArrayList<ComponentName>();
final PackageManager packageManager = (PackageManager) getActivity().getPackageManager();
packageManager.getPreferredActivities(filters, activities, null);
for (ComponentName activity : activities) {
if (myPackageName.equals(activity.getPackageName())) {
return true;
}
}
return false;
}
public static void resetPreferredLauncherAndOpenChooser(Context context) {
PackageManager packageManager = context.getPackageManager();
ComponentName componentName = new ComponentName(context, FakeLauncherActivity.class);
packageManager.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
Intent selector = new Intent(Intent.ACTION_MAIN);
selector.addCategory(Intent.CATEGORY_HOME);
selector.putExtra(EXTRA_MESSAGE, "1");
selector.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(selector);
packageManager.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, PackageManager.DONT_KILL_APP);
}
}
My second file Http.java
package com.ts.techassi.ts;
import android.os.AsyncTask;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Http extends AsyncTask<String, Void, String> {
String USER_AGENT = "Mozilla/5.0";
private TextView scanResults;
#Override
protected String doInBackground(String... url) {
try {
return sendGet();
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}
private String sendGet() throws Exception {
String url = "http://my.url.com";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
// System.out.println(response.toString());
return response.toString();
}
}
EDIT 1:
Changed if( pinString == response) to if( pinString.equals(response))
So I thinks thats all you need. I hope you can help me.
The problem is this line:
if( response == pinString) {
Never compare Strings like this in Java. Change it to:
if( pinString.equals(response) ) {
The reason is that, in Java, == operator compares instances, not contents. It works for primitives (like ints and longs), but Objects, including Strings, need to be compared with the .equals() method, which compares the contents, not the instance.
So I am trying to create an Android app which basically reads out the twitter feed according to the search query inside a UI. The feed that I need to display form the parsed JSON is the user name, handle, profile picture and the tweet.
Now I have created the whole thing and my code compiles but as soon as I run it the app opens and I write something in the search feed and hit enter - " Unfortunately, AppName has stopped working " I am attaching my logcat and my source code for reference.
*Solved the issue by removing set text from DoInBackground and then giving adequate permission for Android to access internet. The issue now is that as I try and display the profile picture, the URL gets displayed, not the image.
Source code :
package com.example.twittersearchactivity;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class TwitterSearchActivity extends Activity {
private TextView tweetDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_twitter_search);
tweetDisplay = (TextView)findViewById(R.id.tweet_txt);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.twitter_search, menu);
return true;
}
public void searchTwitter(View view){
EditText searchTxt = (EditText)findViewById(R.id.search_edit);
String searchTerm = searchTxt.getText().toString();
if(searchTerm.length()>0){
try{
String encodedSearch = URLEncoder.encode(searchTerm, "UTF-8");
String searchURL = "http://search.twitter.com/search.json?q="+encodedSearch;
new GetTweets().execute(searchURL);
Log.i("1", "entered the searchterm");
}
catch(Exception e){
tweetDisplay.setText("Whoops - something went wrong!");
e.printStackTrace();
}
}
else
tweetDisplay.setText("Enter a search query!");
}
private class GetTweets extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... twitterURL) {
StringBuilder tweetFeedBuilder = new StringBuilder();
for (String searchURL : twitterURL) {
HttpClient tweetClient = new DefaultHttpClient();
try {
HttpGet tweetGet = new HttpGet(searchURL);
HttpResponse tweetResponse = tweetClient.execute(tweetGet);
StatusLine searchStatus = tweetResponse.getStatusLine();
if (searchStatus.getStatusCode() == 200) {
HttpEntity tweetEntity = tweetResponse.getEntity();
Log.i("2", "entered gettweets");
InputStream tweetContent = tweetEntity.getContent();
InputStreamReader tweetInput = new InputStreamReader(tweetContent);
BufferedReader tweetReader = new BufferedReader(tweetInput);
String lineIn;
while ((lineIn = tweetReader.readLine()) != null) {
tweetFeedBuilder.append(lineIn);
Log.i("3", "entered while in dobackground");
}
}
else {Log.i("error", "error");}
//tweetDisplay.setText("Whoops - something went wrong!");
}
catch(Exception e) {
Log.e("DEBUGTAG", "Remote Image Exception", e);
//tweetDisplay.setText("Whoops - something went wrong!");
e.printStackTrace();
}}
return tweetFeedBuilder.toString();
}
protected void onPostExecute(String result) {
StringBuilder y;
StringBuilder tweetResultBuilder = new StringBuilder();
try {
Log.i("tag", "entered try block");
JSONObject resultObject = new JSONObject(result);
JSONArray tweetArray = resultObject.getJSONArray("results");
for (int t=0; t<tweetArray.length(); t++) {
Log.i("tag", "entered the json stream");
JSONObject tweetObject = tweetArray.getJSONObject(t);
tweetResultBuilder.append(tweetObject.getString("from_user")+": ");
tweetResultBuilder.append(tweetObject.getString("from_user_name")+": ");
tweetResultBuilder.append(tweetObject.get("text")+"\n\n");
String imageURL = (String) tweetObject.get(("profile_image_url")+": ");
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageURL).getContent());
#SuppressWarnings("deprecation")
Drawable d =new BitmapDrawable(bitmap);
d.setAlpha(255);
TextView.setCompoundDrawablesWithIntrinsicBounds(0,0,1,0);
}
}
catch (Exception e) {
tweetDisplay.setText("Whoops - something went wrong!");
e.printStackTrace();}
if(tweetResultBuilder.length()>0)
tweetDisplay.setText(tweetResultBuilder.toString());
else
tweetDisplay.setText("Sorry - no tweets found for your search!");
}
}}
You can't call view functions like setText on another thread like an AsyncTask doInBackground function. You need to do it in onPostExecute.
I am sending some information from my application to server and waiting for the response. Before i send i set my textview for message to display "processing request" and after getting response i display a different message.
This processing message is not getting displayed. Is it beacuse the UI is getting blocked due to other operation.
How to handle this. Threading is not giving correct result as need to display the response.
SO that involve UI in the thread .
package com.PandG.app.android.activities;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.PandG.app.android.R;
import com.PandG.app.android.dataAccess.SettingsDBAccess;
import com.PandG.app.android.entity.Job;
import com.PandG.app.android.entity.Settings;
import com.PandG.app.android.services.JobsManager;
import com.lib.android.Utils.Utils;
import com.lib.android.activity.BaseActivity;
import com.lib.android.dataAccess.DatabaseManager;
public class JobCheckoutActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setViewContent();
}
private void setViewContent() {
Settings setting = getSettings();
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.job_checkout);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.customtitle);
//new DataProcess().execute(null);
TextView text1 = (TextView)findViewById(R.id.checkoutmessage);
text1.setText("Processiong Job Cart ...");
if(setting!=null){
TextView text2 = (TextView)findViewById(R.id.checkoutheading);
text2.setVisibility(View.GONE);
Button homeButton = (Button)findViewById(R.id.gohome);
homeButton.setVisibility(View.GONE);
JSONObject jobObject =encodeData(setting);
sendDataToServer(jobObject);
}
}
private void sendDataToServer(JSONObject jobObject) {
TextView text1 = (TextView)findViewById(R.id.checkoutmessage);
text1.setText("Processiong Job Cart ...");
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
// Limit
HttpResponse response;
try {
HttpPost post = new HttpPost(Utils.getPostUrl());
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("orderparameters",
jobObject.toString()));
Log.i("Job ORDER", jobObject.toString());
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = client.execute(post);
checkResponseFromServer(response);
ClearCart();
} catch (Exception e) {
Log.w("error", "connection failed");
Toast.makeText(this, "Order not placed due to connection error",
Toast.LENGTH_LONG);
e.printStackTrace();
}
}
private void ClearCart() {
JobsManager.JobsCartList.clear();
}
private void checkResponseFromServer(HttpResponse response) {
try {
if (response != null) {
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
in.close();
JSONObject jsonResponse = new JSONObject(buffer.toString());
Log.i("Status", jsonResponse.getString("status"));
Log.i("Status", jsonResponse.getString("message"));
Log.i("Status", jsonResponse.getString("debug"));
TextView text1 = (TextView)findViewById(R.id.checkoutheading);
text1.setVisibility(View.VISIBLE);
TextView text = (TextView) findViewById(R.id.checkoutmessage);
if (jsonResponse.getString("status").equals("SUCC")) {
text.setText( Html.fromHtml(getString(R.string.checkout_body1)));
} else
text.setText(jsonResponse.getString("message")
+ jsonResponse.getString("debug"));
}
} catch (Exception ex) {
}
}
private JSONObject encodeData(Settings setting) {
JSONObject jobObject = new JSONObject();
try {
JSONObject jobject = new JSONObject();
jobject.put("name", setting.getName());
jobject.put("email", setting.getEmail());
jobject.put("phone", setting.getPhone());
jobject.put("school", setting.getSchool());
jobject.put("major", setting.getMajor());
jobObject.put("customer", jobject);
JSONArray jobsarray = new JSONArray();
for (Job job : JobsManager.JobsCartList) {
JSONObject jobEntry = new JSONObject();
jobEntry.put("jobtitle",job.getTitle());
jobEntry.put("qty","1");
jobsarray.put(jobEntry);
}
jobObject.put("orders", jobsarray);
} catch (JSONException ex) {
}
return jobObject;
}
private Settings getSettings() {
SettingsDBAccess settingsDBAccess = new SettingsDBAccess(
DatabaseManager.getInstance());
Settings setting = settingsDBAccess.getSetting();
if (setting==null){
startActivityForResult((new Intent(this,SettingsActivity.class)),Utils
.getDefaultRequestCode());
}
return setting;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Settings setting = new SettingsDBAccess(
DatabaseManager.getInstance()).getSetting();
if(setting!=null){
JSONObject jobObject = encodeData(setting);
sendDataToServer(jobObject);
}
}
/* private class DataProcess extends AsyncTask {
#Override
protected void onPostExecute(Object result) {
}
#Override
protected Object doInBackground(Object... arg0) {
processDataandsend();
return null;
}
private void processDataandsend() {
Settings setting = getSettings();
if(setting!=null){
TextView text2 = (TextView)findViewById(R.id.checkoutheading);
text2.setVisibility(View.GONE);
Button homeButton = (Button)findViewById(R.id.gohome);
homeButton.setVisibility(View.GONE);
JSONObject jobObject =encodeData(setting);
sendDataToServer(jobObject);
}
}
} */
}
You should not perform HTTP-work on the UI-thread. Instead use AsyncTask
In your AsyncTask you are only allowed to update the UI in two places:
#Override
protected void onPreExecute()
TextView.setText("Beginning HTTP-work..Please wait");
{
and
#Override
protected void onPostExecute(Void v) {
TextView.setText("Done..SUCCESS!");
}
Use these two to update the UI before and after the HTTP-work has been done.
Long operations must be in background. Best way to implement this on Android, use AsyncTask, for more information: http://developer.android.com/reference/android/os/AsyncTask.html