send mms by code not using intent - android

I copy all code form mms pacakge in android open source, then i using these code to send mms:
public class Mms_sampleActivity extends Activity {
String subject = "test MMS ";
String recipient = "13534585169"; //13800138000
SendReq sendRequest;
EncodedStringValue[] sub;
byte[] bytesToSend;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MMmakePdu();
}
void MMmakePdu()
{
sendRequest = new SendReq();
sub = EncodedStringValue.extract(subject);
if (sub != null & sub.length != 0) {
sendRequest.setSubject(sub[0]);
}
EncodedStringValue[] phoneNumbers = EncodedStringValue.extract(recipient);
if (phoneNumbers != null & phoneNumbers.length != 0)
{
sendRequest.addTo(phoneNumbers[0]);
}
PduBody pduBody = new PduBody();
PduPart part = new PduPart();
part.setName("sample".getBytes());
part.setContentType("image/png".getBytes());
String furl = "file://mnt/sdcard//1.png";
PduPart partPdu = new PduPart();
partPdu.setCharset(CharacterSets.UTF_8);
partPdu.setName(part.getName());
partPdu.setContentType(part.getContentType());
partPdu.setDataUri(Uri.parse(furl));
pduBody.addPart(partPdu);
sendRequest.setBody(pduBody);
PduComposer composer = new PduComposer(this, sendRequest);
bytesToSend = composer.make();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try{
SendMMS.sendMMMS(Mms_sampleActivity.this, bytesToSend);
}catch (Exception e){
e.printStackTrace();
}
}
});
t.start();
}
}
public class SendMMS {
public static String mmscUrl = "http://mmsc.monternet.com";
//public static String mmscUrl = "http://mmsc.myuni.com.cn";
//public static String mmscUrl = "http://www.baidu.com";
public static String mmsProxy = "10.0.0.172";
public static String mmsPort = "80";
private static String HDR_VALUE_ACCEPT_LANGUAGE = "";
private static final String HDR__KEY_ACCEPT = "Accept";
private static final String HDR_KEY_ACCEPT_LANGUAGE = "Accept-Language";
private static final String HDR_VALUE_ACCEPT =
"*/*, application/vnd.wap.mms-message, application/vnd.wap.sic";
public static byte[] sendMMMS(Context context, byte[] pdu) throws Exception
{
//HDR_AVLUE_ACCEPT_LANGUAGE = getHttpAcceptLanguage();
if (mmscUrl == null)
{
throw new IllegalAccessException("URL must not be null");
}
HttpClient client = null;
try{
//client = AndroidHttpClient.newInstance("Android-Mms/2.0");
//client = HttpConnector.buileClient(context);
URI hostUrl = new URI(mmscUrl);
HttpHost target = new HttpHost(
hostUrl.getHost(), hostUrl.getPort(),
HttpHost.DEFAULT_SCHEME_NAME);
client = AndroidHttpClient.newInstance("Android-Mms/2.0");
HttpPost post = new HttpPost(mmscUrl);
ByteArrayEntity entity = new ByteArrayEntity(pdu);
entity.setContentType("application/vnd.wap.mms-message");
post.setEntity(entity);
post.addHeader(HDR__KEY_ACCEPT,HDR_VALUE_ACCEPT);
post.addHeader(HDR_KEY_ACCEPT_LANGUAGE, HDR_VALUE_ACCEPT_LANGUAGE);
HttpParams params = client.getParams();
HttpProtocolParams.setContentCharset(params, "UTF-8");
ConnRouteParams.setDefaultProxy(
params, new HttpHost(mmsProxy, 80));
//req.setParams(params);
HttpResponse response = client.execute(target,post);
StatusLine status = response.getStatusLine();
System.out.println("status : " + status.getStatusCode());
if (status.getStatusCode() != 200)
{
System.out.println("!200");
throw new IOException("HTTP error: " + status.getReasonPhrase());
}
HttpEntity resentity = response.getEntity();
byte[] body = null;
if (resentity != null)
{
try{
if (resentity.getContentLength() <= 0)
{
body = new byte[(int)resentity.getContentLength()];
DataInputStream dis = new DataInputStream(resentity.getContent());
try{
dis.readFully(body);
}finally{
try{
dis.close();
}catch (IOException e)
{
e.printStackTrace();
}
}
}
}finally
{
if (entity != null)
entity.consumeContent();
}
}
System.out.println("result : "+ new String(body));
return body;
}catch (Exception e)
{
e.printStackTrace();
}
return new byte[0];
}
}
my code run without any mistake,but give me status.getStatusCode()=400,i don't know if my partPdu is mistake or my httppost is mistake,can you give me some advice?

Related

How to get All Registered users, not only my contact lists on Firebase in my code

I have this FetchMyUsersService Class, This class gets only users on my contact list, how i can get all Firebase users ? Please Help.
This is my Code
This is Dont written by me.
I Have more classes, but i think this my solution in this class, If not just tell me i share another classes on this project
public class FetchMyUsersService extends IntentService {
private static String EXTRA_PARAM1 = "my_id";
private static String EXTRA_PARAM2 = "token";
private HashMap<String, Contact> myContacts;
private ArrayList<User> myUsers;
private String myId, idToken;
public static boolean STARTED = false;
public FetchMyUsersService() {
super("FetchMyUsersService");
}
public static void startMyUsersService(Context context, String myId, String idToken) {
Intent intent = new Intent(context, FetchMyUsersService.class);
intent.putExtra(EXTRA_PARAM1, myId);
intent.putExtra(EXTRA_PARAM2, idToken);
context.startService(intent);
}
#Override
protected void onHandleIntent(Intent intent) {
STARTED = true;
myId = intent.getStringExtra(EXTRA_PARAM1);
idToken = intent.getStringExtra(EXTRA_PARAM2);
fetchMyContacts();
broadcastMyContacts();
fetchMyUsers();
broadcastMyUsers();
STARTED = false;
}
private void broadcastMyUsers() {
if (this.myUsers != null) {
Intent intent = new Intent(Helper.BROADCAST_MY_USERS);
intent.putParcelableArrayListExtra("data", this.myUsers);
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
localBroadcastManager.sendBroadcast(intent);
}
}
private void fetchMyUsers() {
myUsers = new ArrayList<>();
try {
StringBuilder response = new StringBuilder();
URL url = new URL(FirebaseDatabase.getInstance().getReference().toString() + "/" + Helper.REF_USERS + ".json?auth=" + idToken);
URLConnection conn = url.openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
response.append(line).append(" ");
}
rd.close();
JSONObject responseObject = new JSONObject(response.toString());
Gson gson = new GsonBuilder().create();
Iterator<String> keys = responseObject.keys();
while (keys.hasNext()) {
String key = keys.next();
JSONObject innerJObject = responseObject.getJSONObject(key);
User user = gson.fromJson(innerJObject.toString(), User.class);
if (User.validate(user) && !user.getId().equals(myId)) {
String idTrim = Helper.getEndTrim(user.getId());
if (myContacts.containsKey(idTrim)) {
user.setNameInPhone(myContacts.get(idTrim).getName());
myUsers.add(user);
}
}
if (myUsers.size() == myContacts.size()) {
break;
}
}
Collections.sort(myUsers, new Comparator<User>() {
#Override
public int compare(User user1, User user2) {
return user1.getNameToDisplay().compareToIgnoreCase(user2.getNameToDisplay());
}
});
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
private void broadcastMyContacts() {
if (this.myContacts != null) {
new Helper(this).setMyUsersNameCache(myContacts);
Intent intent = new Intent(Helper.BROADCAST_MY_CONTACTS);
intent.putExtra("data", this.myContacts);
LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
localBroadcastManager.sendBroadcast(intent);
}
}
private void fetchMyContacts() {
myContacts = new HashMap<>();
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if (cursor != null && !cursor.isClosed()) {
cursor.getCount();
while (cursor.moveToNext()) {
int hasPhoneNumber = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (hasPhoneNumber == 1) {
String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replaceAll("\\s+", "");
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY));
if (Patterns.PHONE.matcher(number).matches()) {
boolean hasPlus = String.valueOf(number.charAt(0)).equals("+");
number = number.replaceAll("[\\D]", "");
if (hasPlus) {
number = "+" + number;
}
Contact contact = new Contact(number, name);
String endTrim = Helper.getEndTrim(contact.getPhoneNumber());
if (!myContacts.containsKey(endTrim))
myContacts.put(endTrim, contact);
}
}
}
cursor.close();
}
}
}
Please try changing the code of your fetchMyUsers() like bellow
private void fetchMyUsers() {
myUsers = new ArrayList<>();
try {
StringBuilder response = new StringBuilder();
URL url = new URL(FirebaseDatabase.getInstance().getReference().toString() + "/" + Helper.REF_USERS + ".json?auth=" + idToken);
URLConnection conn = url.openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
response.append(line).append(" ");
}
rd.close();
JSONObject responseObject = new JSONObject(response.toString());
Gson gson = new GsonBuilder().create();
Iterator<String> keys = responseObject.keys();
while (keys.hasNext()) {
String key = keys.next();
JSONObject innerJObject = responseObject.getJSONObject(key);
User user = gson.fromJson(innerJObject.toString(), User.class);
myUsers.add(user);
if (myUsers.size() == myContacts.size()) {
break;
}
}
Collections.sort(myUsers, new Comparator<User>() {
#Override
public int compare(User user1, User user2) {
return user1.getNameToDisplay().compareToIgnoreCase(user2.getNameToDisplay());
}
});
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}

Vertical Progress Bar on Android

I want to implement progress bar on list view for data that am getting from Mysql server here is my code any new suggestion are welcome for an example change your layout or anything which will make implementation easy as am neophyte
public class teststatusActivity extends BaseActivity {
String myJSON = "" ;
private static final String TAG_RESULTS = "result";
private static final String TAG_TICKET = "ticket_id";
private static final String TAG_Status = "ticket_status";
private static final String TAG_Status1 = "ticket_status1";
private static final String TAG_Status2 = "ticket_status2";
private static final String TAG_Status3 = "ticket_status3";
private static final String TAG_I = "";
public static final String DATA_URL = "http://103.3.62.23/complain_dashboard/api/getTicketStatus.php?ticket_id=";
public String ticketID;
JSONArray peoples = null;
ListView list;
ArrayList<HashMap<String, String>> usersList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_teststatus);
list = (ListView) findViewById(R.id.listView);
usersList = new ArrayList<HashMap<String, String>>();
getData();
}
protected void showList() {
try {
JSONObject jsonObj = new JSONObject(myJSON);
JSONObject pe = jsonObj.getJSONObject(TAG_RESULTS);
String id = pe.getString("ticket_id");
String status = pe.getString("ticket_status");
String stat = null;
String stat1 = null;
String stat2 = null;
String stat3 = null;
if (pe.get("ticket_status").equals("0")) {
stat = "Feedback Sent To Team";
}
if (pe.get("ticket_status").equals("1")) {
stat1 = "Technical Team is Working on it";
}
if (pe.get("ticket_status").equals("2")) {
stat2 = "Your Report is About To Resolve";
}
if (pe.get("ticket_status").equals("3")) {
stat3 = "Resolved";
}
HashMap<String, String> users = new HashMap<String, String>();
users.put( TAG_TICKET , id );
users.put(TAG_Status, stat );
users.put(TAG_Status1, stat1 );
users.put(TAG_Status2, stat2);
users.put(TAG_Status3, stat3);
usersList.add(users);
ListAdapter adapter = new SimpleAdapter(
teststatusActivity.this, usersList, R.layout.list_item,
new String[]{TAG_TICKET, TAG_Status,TAG_Status1, TAG_Status2, TAG_Status3 },
new int[]{R.id.feed, R.id.feedS, R.id.feedwork, R.id.abouttoresolve, R.id.resolved}
);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData() {
class GetDataJSON extends AsyncTask<String, Void, String> {
SharedPreferences sharedPref = getSharedPreferences("tcktid", Context.MODE_WORLD_READABLE);
final String ticket =sharedPref.getString("tid", null);
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost(DATA_URL + ticket);
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (Exception squish) {
}
}
return result;
}
#Override
protected void onPostExecute(String result) {
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
} ;

How to Pass Context OF one Activity to Another Non Activity Class In Android

hello i want to get string from activity and set it to the another non activity class please help me i am adding my code.and i need to set the edittext value in non activity class url. help me
my activity.
public class AlertForIp extends AppCompatActivity {
String value;
private Button mButton;
final Context c = this;
static String urlString;
private static AlertForIp instance;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog);
instance = this;
final EditText input = new EditText(AlertForIp.this);
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertForIp.this);
//AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
/* SharedPreferences prefss = PreferenceManager.getDefaultSharedPreferences(AlertForIp.this);
final SharedPreferences.Editor editor = prefss.edit();*/
value = input.getText().toString();
// Setting Dialog Title
String urlsss="http://";
String urls=":1219/Json/Handler.ashx";
// This above url string i need to set in that class
urlString = urlsss+value+urls;
/* editor.putString("stringid", urlString); //InputString: from the EditText
editor.commit();
*/
alertDialog.setTitle("WELCOME TO RESTROSOFT");
// Setting Dialog Message
alertDialog.setMessage("ENTER YOUR IP");
//final EditText input = new EditText(this);
//alertDialog.setView(input);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
//input.setText("http://");
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end,
android.text.Spanned dest, int dstart, int dend) {
if (end > start) {
String destTxt = dest.toString();
String resultingTxt = destTxt.substring(0, dstart)
+ source.subSequence(start, end)
+ destTxt.substring(dend);
if (!resultingTxt
.matches("^\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3})?)?)?)?)?)?")) {
return "";
} else {
String[] splits = resultingTxt.split("\\.");
for (int i = 0; i < splits.length; i++) {
if (Integer.valueOf(splits[i]) > 255) {
Toast.makeText(AlertForIp.this, "Please enter valid ip", Toast.LENGTH_SHORT).show();
return "";
}
}
}
}
return null;
}
};
input.setFilters(filters);
//input.setText(ip);
alertDialog.setView(input); //
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.waiting);
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
/*if(input.getText().length()==0)
{
input.setError("Field cannot be left blank.");
dialog.dismiss();
}*/
String validation="^\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3})?)?)?)?";
if (value.matches(validation))
{
Toast.makeText(getApplicationContext(),"enter valid IP address",Toast.LENGTH_SHORT).show();
Intent inten = new Intent(AlertForIp.this, AlertForIp.class);
startActivity(inten);
// or
}
else if(!input.getText().toString().equals(""))
{
Intent intent = new Intent(AlertForIp.this, Sample.class);
startActivity(intent);
//Toast.makeText(AlertDialogForIp.this, "Input Text Is Empty.. Please Enter Some Text", Toast.LENGTH_SHORT).show();
}
else
{
Intent inten = new Intent(AlertForIp.this, AlertForIp.class);
startActivity(inten);
Toast.makeText(AlertForIp.this, "Input Text Is Empty.. Please Enter Some Text", Toast.LENGTH_SHORT).show();
}
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
//dialog.cancel();
finish();
}
});
// closed
// Showing Alert Message
alertDialog.show();
}
public static Context getContext() {
RestAPI rss=new RestAPI();
rss.persistItems(urlString);
return instance.getApplicationContext();
}
}
And here is my no activity class
public class RestAPI {
String urlString;
//String data;
public void persistItems(String info) {
Context context = AlertForIp.getContext();
/* SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
data = prefs.getString("stringid", "no id");*/
urlString=info;
}
//private final String urlString = "http://10.0.2.2:1219/Json/Handler.ashx";
private static String convertStreamToUTF8String(InputStream stream) throws IOException {
String result = "";
StringBuilder sb = new StringBuilder();
try {
InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[4096];
int readedChars = 0;
while (readedChars != -1) {
readedChars = reader.read(buffer);
if (readedChars > 0)
sb.append(buffer, 0, readedChars);
}
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
private String load(String contents) throws IOException {
//i want to add that urlstring here;
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(60000);
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter w = new OutputStreamWriter(conn.getOutputStream());
w.write(contents);
w.flush();
InputStream istream = conn.getInputStream();
String result = convertStreamToUTF8String(istream);
return result;
}
private Object mapObject(Object o) {
Object finalValue = null;
if (o.getClass() == String.class) {
finalValue = o;
} else if (Number.class.isInstance(o)) {
finalValue = String.valueOf(o);
} else if (Date.class.isInstance(o)) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss", new Locale("en", "USA"));
finalValue = sdf.format((Date) o);
} else if (Collection.class.isInstance(o)) {
Collection<?> col = (Collection<?>) o;
JSONArray jarray = new JSONArray();
for (Object item : col) {
jarray.put(mapObject(item));
}
finalValue = jarray;
} else {
Map<String, Object> map = new HashMap<String, Object>();
Method[] methods = o.getClass().getMethods();
for (Method method : methods) {
if (method.getDeclaringClass() == o.getClass()
&& method.getModifiers() == Modifier.PUBLIC
&& method.getName().startsWith("get")) {
String key = method.getName().substring(3);
try {
Object obj = method.invoke(o, null);
Object value = mapObject(obj);
map.put(key, value);
finalValue = new JSONObject(map);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return finalValue;
}
public JSONObject CreateNewAccount(String User_Name, String Password) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface", "RestAPI");
o.put("method", "CreateNewAccount");
p.put("User_Name", mapObject(User_Name));
p.put("Password", mapObject(Password));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
This is my another Activity i have created the instance of restApi
public class UserDetailsActivity extends Activity {
TextView tvFisrtName, tvLastName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_details);
// Show the Up button in the action bar.
//setupActionBar();
tvFisrtName=(TextView)findViewById(R.id.tv_firstname);
tvLastName=(TextView)findViewById(R.id.tv_lastname);
Intent i=getIntent();
String username=i.getStringExtra("User_Name");
new AsyncUserDetails().execute(username);
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
//getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
protected class AsyncUserDetails extends AsyncTask<String,Void,JSONObject>
{
String str1;
#Override
protected JSONObject doInBackground(String... params) {
// TODO Auto-generated method stub
JSONObject jsonObj = null;
//here i have error
RestAPI api = new RestAPI();
try {
jsonObj = api.GetUserDetails(params[0]);
//JSONParser parser = new JSONParser();
//userDetail = parser.parseUserDetails(jsonObj);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncUserDetails", e.getMessage());
}
return jsonObj;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
try {
JSONObject jsonObj=result.getJSONArray("Value").getJSONObject(0);
str1=jsonObj.getString("user_id").toString();
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(UserDetailsActivity.this, str1, Toast.LENGTH_SHORT).show();
tvFisrtName.setText(str1);
}
}
public class RestAPI {
String url;
// create constructor here
public RestAPI(String url){
this.url=url;
}
String urlString;
//String data;
public void persistItems(String info) {
Context context = AlertForIp.getContext();
/* SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
data = prefs.getString("stringid", "no id");*/
urlString=info;
}
//private final String urlString = "http://10.0.2.2:1219/Json/Handler.ashx";
private static String convertStreamToUTF8String(InputStream stream) throws IOException {
String result = "";
StringBuilder sb = new StringBuilder();
try {
InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[4096];
int readedChars = 0;
while (readedChars != -1) {
readedChars = reader.read(buffer);
if (readedChars > 0)
sb.append(buffer, 0, readedChars);
}
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return result;
}
private String load(String contents) throws IOException {
//i want to add that urlstring here;
now you can use here url directly
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(60000);
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStreamWriter w = new OutputStreamWriter(conn.getOutputStream());
w.write(contents);
w.flush();
InputStream istream = conn.getInputStream();
String result = convertStreamToUTF8String(istream);
return result;
}
private Object mapObject(Object o) {
Object finalValue = null;
if (o.getClass() == String.class) {
finalValue = o;
} else if (Number.class.isInstance(o)) {
finalValue = String.valueOf(o);
} else if (Date.class.isInstance(o)) {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss", new Locale("en", "USA"));
finalValue = sdf.format((Date) o);
} else if (Collection.class.isInstance(o)) {
Collection<?> col = (Collection<?>) o;
JSONArray jarray = new JSONArray();
for (Object item : col) {
jarray.put(mapObject(item));
}
finalValue = jarray;
} else {
Map<String, Object> map = new HashMap<String, Object>();
Method[] methods = o.getClass().getMethods();
for (Method method : methods) {
if (method.getDeclaringClass() == o.getClass()
&& method.getModifiers() == Modifier.PUBLIC
&& method.getName().startsWith("get")) {
String key = method.getName().substring(3);
try {
Object obj = method.invoke(o, null);
Object value = mapObject(obj);
map.put(key, value);
finalValue = new JSONObject(map);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return finalValue;
}
public JSONObject CreateNewAccount(String User_Name, String Password) throws Exception {
JSONObject result = null;
JSONObject o = new JSONObject();
JSONObject p = new JSONObject();
o.put("interface", "RestAPI");
o.put("method", "CreateNewAccount");
p.put("User_Name", mapObject(User_Name));
p.put("Password", mapObject(Password));
o.put("parameters", p);
String s = o.toString();
String r = load(s);
result = new JSONObject(r);
return result;
}
use here
RestAPI rss=new RestAPI(urlString );

how to resume and stop web service asynctask in android

I have list view in which I am placing images which is in server using web service asynctask. the images are placed . whenever I try to click on list view over image its getting stucked in emulator and phone..
WebServiceTask wst = new WebServiceTask(WebServiceTask.GET_TASK, this, "Loading.....");
wst.execute(new String[]{sampleURL});
private class WebServiceTask extends AsyncTask<String, Integer, String> {
public static final int POST_TASK = 1;
public static final int GET_TASK = 2;
private static final String TAG = "WebServiceTask";
// connection timeout, in milliseconds (waiting to connect)
private static final int CONN_TIMEOUT = 3000;
// socket timeout, in milliseconds (waiting for data)
private static final int SOCKET_TIMEOUT = 5000;
private int taskType = GET_TASK;
private Context mContext = null;
private String processMessage = "Processing...";
private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
private ProgressDialog pDlg = null;
public WebServiceTask(int taskType, Context mContext, String processMessage) {
this.taskType = taskType;
this.mContext = mContext;
this.processMessage = processMessage;
}
public void addNameValuePair(String name, String value) {
params.add(new BasicNameValuePair(name, value));
}
private void showProgressDialog() {
pDlg = new ProgressDialog(mContext);
pDlg.setMessage(processMessage);
pDlg.setProgressDrawable(mContext.getWallpaper());
pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDlg.setCancelable(false);
pDlg.show();
}
#Override
protected void onPreExecute() {
//hideKeyboard();
showProgressDialog();
}
protected String doInBackground(String... urls) {
String url = urls[0];
String result = "";
HttpResponse response = doResponse(url);
if (response == null) {
return result;
} else {
try {
result = inputStreamToString(response.getEntity().getContent());
} catch (IllegalStateException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
return result;
}
#Override
protected void onPostExecute(String response) {
handleResponse(response);
//aa.clear();
pDlg.dismiss();
}
// Establish connection and socket (data retrieval) timeouts
private HttpParams getHttpParams() {
HttpParams htpp = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
return htpp;
}
private HttpResponse doResponse(String url) {
// Use our connection and data timeouts as parameters for our
// DefaultHttpClient
HttpClient httpclient = new DefaultHttpClient(getHttpParams());
HttpResponse response = null;
try {
switch (taskType) {
case POST_TASK:
HttpPost httppost = new HttpPost(url);
//httppost.setHeader("Authorization","" );
//httppost.addHeader("Authorization", apikey);
httppost.setEntity(new UrlEncodedFormEntity(params));
response = httpclient.execute(httppost);
break;
case GET_TASK:
HttpGet httpget = new HttpGet(url);
//httpget.addHeader("Authorization", apikey);
//httpget.setHeader("Authorization",apikey );
response = httpclient.execute(httpget);
break;
}
} catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
return response;
}
public void handleResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
JSONArray jso = jsonObject.getJSONArray("search_result");
if(jso.length() != 0) {
for (int i = 0; i < jso.length(); i++) {
Person resultRow = new Person();
resultRow.id = jso.getJSONObject(i).getString("property_id");
resultRow.ProjectName = jso.getJSONObject(i).getString("property_name");
JSONObject ppty_image_object = jso.getJSONObject(i);
JSONArray ppty_image_array = ppty_image_object.getJSONArray("property_image");
for (int j = 0; j < ppty_image_array.length(); j++) {
resultRow.logo =ppty_image_array.getJSONObject(j).getString("image");
// resultRow.logo[j] = ppty_image_array.getJSONObject(j).getString("image");
}
// resultRow.logo =jso.getJSONObject(i).getString("image");
resultRow.id = jso.getJSONObject(i).getString("user_id");
resultRow.ProjectName = jso.getJSONObject(i).getString("property_name");
resultRow.bathrooms = jso.getJSONObject(i).getString("bathrooms");
resultRow.Host_Name = jso.getJSONObject(i).getString("user_name");
resultRow.city = jso.getJSONObject(i).getString("city");
resultRow.price = jso.getJSONObject(i).getString("price");
resultRow.bed = jso.getJSONObject(i).getString("bed");
resultRow.bedrooms = jso.getJSONObject(i).getString("bedrooms");
resultRow.guest_allow = jso.getJSONObject(i).getString("guest_allow");
resultRow.roomtype = jso.getJSONObject(i).getString("room_type");
resultRow.property_type = jso.getJSONObject(i).getString("property_type");
resultRow.user_ppty_id = jso.getJSONObject(i).getString("property_id");
resultRow.check_in_time = jso.getJSONObject(i).getString("check_in_time");
resultRow.check_out_time = jso.getJSONObject(i).getString("check_out_time");
if(jso.getJSONObject(i).getString("host_image").toString().equals("{}")){
resultRow.host_image= (getResources().getDrawable(R.drawable.close)).toString();
}else {
resultRow.host_image = jso.getJSONObject(i).getString("host_image");
}
ImageAdapter adapter = new ImageAdapter(this);
resultRow.city = jso.getJSONObject(i).getString("city");
resultRow.descrip = jso.getJSONObject(i).getString("description");
resultRow.latitude=jso.getJSONObject(i).getString("latitude");
resultRow.longlati=jso.optJSONObject(i).getString("longitude");
resultRow.minstay=jso.getJSONObject(i).getString("minimum_stay");
resultRow.cancelation=jso.getJSONObject(i).getString("cancellation_policy");
resultRow.houserules=jso.getJSONObject(i).getString("house_rules");
// resultRow.logo=jso.getJSONObject(i).getString("logo");
arrayOfwebData.add(resultRow);
}
}
}
catch (NullPointerException np){
Log.e(TAG, np.getLocalizedMessage(), np);
}
catch (Exception e) {
Log.e(TAG, e.getLocalizedMessage(), e);
}
ListView myListView = (ListView)findViewById(R.id.listview);
aa=new FancyAdapter();
myListView.setAdapter(aa);
// ViewHolder aa1= new ViewHolder();
}
I want to stop and resume background running process whenever I try to click on list view row it will redirect to next page and whenever I press back button doing background will be resume..
anyone help me.

Android Async Task Freezes UI Completely

I have an Async task that loads information from the server and displays data on the UI. Suddenly the async task downloads the data and formats the JSON data fine but it would freeze the UI completely.
Here is the base download class
public class GetRawData {
private static String LOG_TAG = GetRawData.class.getSimpleName();
private String mRawURL;
private List<NameValuePair> mRawParams = null;
private String mRawData;
private DownloadStatus mDownloadStatus;
public GetRawData(String mRawURL) {
this.mRawURL = mRawURL;
this.mRawParams = null;
this.mDownloadStatus = DownloadStatus.IDLE;
}
public String getRawData() {
return mRawData;
}
public void setRawURL(String mRawURL) {
this.mRawURL = mRawURL;
}
public List<NameValuePair> getRawParams() {
return mRawParams;
}
public void setRawParams(List<NameValuePair> mParams) {
this.mRawParams = mParams;
}
public DownloadStatus getDownloadStatus() {
return mDownloadStatus;
}
public void reset() {
this.mRawURL = null;
this.mRawData = null;
this.mDownloadStatus = DownloadStatus.IDLE;
}
public void execute() {
this.mDownloadStatus = DownloadStatus.PROCESSING;
DownloadRawData mDownloadRawData = new DownloadRawData();
mDownloadRawData.execute(mRawURL);
}
public class DownloadRawData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// Create URL and Reader instances.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
//If no parameter has been provided, return null.
if (params == null)
return null;
try {
// Get URL entered by the user.
URL mURL = new URL(params[0]);
urlConnection = (HttpURLConnection) mURL.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.setConnectTimeout(10000);
urlConnection.setReadTimeout(10000);
urlConnection.setRequestProperty("Content-Type","application/json");
//urlConnection.setRequestProperty("Host", "android.schoolportal.gr");
urlConnection.connect();
// validate and add parameters if available.
if (mRawParams != null && mRawParams.size()>0){
JSONObject jsonParam = new JSONObject();
for (NameValuePair pair : mRawParams) {
jsonParam.put(pair.getName().toString(), pair.getValue().toString());
}
String jsonparams = jsonParam.toString();
// Send POST output.
DataOutputStream printout;
printout = new DataOutputStream(urlConnection.getOutputStream());
printout.writeBytes(jsonparams);
printout.flush();
printout.close();
}
int HttpResult =urlConnection.getResponseCode();
StringBuffer buffer = new StringBuffer();
if(HttpResult ==HttpURLConnection.HTTP_OK){
InputStream inputStream = urlConnection.getInputStream();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
System.out.println(""+buffer.toString());
}else{
InputStream errorStream = urlConnection.getErrorStream();
if (errorStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(errorStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
System.out.println(urlConnection.getResponseMessage());
}
return buffer.toString();
} catch (IOException e) {
Log.d("IOException", e.toString());
return null;
} catch (JSONException j) {
Log.d("JSONException", j.toString());
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
Log.d("IOException", "unable to close the reader");
}
}
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mRawData = result;
//Log.d("onPostExecute", result);
if (mRawData == null) {
if (mRawURL == null) {
mDownloadStatus = DownloadStatus.NOT_INITIALIZED;
} else {
mDownloadStatus = DownloadStatus.FAILED_OR_EMPTY;
}
} else {
mDownloadStatus = DownloadStatus.PROCESSED;
}
}
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
}
}
enum DownloadStatus {
IDLE,
PROCESSING,
NOT_INITIALIZED,
FAILED_OR_EMPTY,
PROCESSED
}
Here is the specific data formatting class the extends above class
public class GetJobCardJsonData extends GetRawData {
private static String LOG_TAG = GetAuthenticationJsonData.class.getSimpleName();
private static String JOBCARD_SERVICE_URL = "http://www.appservice.com/appservice/jobcardinfoservice.asmx/GetJobCardInfo";
private List<JobCard> mJobCardList;
private CarcalDownloadListener mListener;
public GetJobCardJsonData(String CurrentDate, int DealershipID) {
super(null);
List<NameValuePair> mParams = new ArrayList<NameValuePair>();
mParams.add(new BasicNameValuePair("JobCardDate", CurrentDate));
mParams.add(new BasicNameValuePair("DealershipID", String.valueOf(DealershipID)));
this.setRawParams(mParams);
}
public List<JobCard> getJobCardList() {
return mJobCardList;
}
public void getjobcards() {
super.setRawURL(JOBCARD_SERVICE_URL);
DownloadJobCardJsonData mDownloadJobCardJsonData = new DownloadJobCardJsonData();
mDownloadJobCardJsonData.execute(JOBCARD_SERVICE_URL);
}
public void setOnCarcalDownloadListener(CarcalDownloadListener onCarcalDownloadListener) {
this.mListener = onCarcalDownloadListener;
}
private void processResult() {
if (getDownloadStatus() != DownloadStatus.PROCESSED) {
Log.e(LOG_TAG, "Error Downloading the raw file.");
return;
}
if (mJobCardList == null){
mJobCardList = new ArrayList<JobCard>();
}
final String JOBCARD_JOBCARDID = "JobCardID";
final String JOBCARD_GETSTOCKNUMBER_WITH_DELIVERYTIME = "StockNumberWithDeliveryTime";
final String JOBCARD_CUSTOMERNAME = "CustomerName";
final String JOBCARD_MODELNUMBER = "ModelNumber";
final String JOBCARD_COLOR = "Color";
final String JOBCARD_SALEEXECUTIVE = "SaleExecutive";
final String JOBCARD_ORDERSTATUS = "OrderStatus";
final String JOBCARD_SHOWROOMSTATUS = "ShowRoomStatus";
try {
JSONArray jsonArray = new JSONArray(getRawData());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jobcarditem = jsonArray.optJSONObject(i);
Long JOBCARDID = jobcarditem.getLong(JOBCARD_JOBCARDID);
String STOCKWITHDELIVERY = jobcarditem.getString(JOBCARD_GETSTOCKNUMBER_WITH_DELIVERYTIME);
String CUSTOMERNAME = jobcarditem.getString(JOBCARD_CUSTOMERNAME);
String MODELNUMBER = jobcarditem.getString(JOBCARD_MODELNUMBER);
String COLOR = jobcarditem.getString(JOBCARD_COLOR);
String SALEEXECUTIVE = jobcarditem.getString(JOBCARD_SALEEXECUTIVE);
int ORDERSTATUS = jobcarditem.getInt(JOBCARD_ORDERSTATUS);
int SHOWROOMSTATUS = jobcarditem.getInt(JOBCARD_SHOWROOMSTATUS);
JobCard mJobCard = new JobCard(JOBCARDID, STOCKWITHDELIVERY, CUSTOMERNAME, MODELNUMBER, COLOR, SALEEXECUTIVE, ORDERSTATUS, SHOWROOMSTATUS);
mJobCardList.add(mJobCard);
}
} catch (JSONException jsone) {
jsone.printStackTrace();
Log.e(LOG_TAG, "Error processing json data.");
}
}
public class DownloadJobCardJsonData extends DownloadRawData {
#Override
protected String doInBackground(String... params) {
return super.doInBackground(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
processResult();
mListener.OnDownloadCompleted();
}
}
}
Here is the code that is called on the activity
private JobCardRecyclerViewAdapter mJobCardRecyclerViewAdapter;
private GetJobCardJsonData mGetJobCardJsonData;
SessionManager session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_job_card_calender);
activateToolbarWithHomeEnabled();
String formattedDate="";
if (session.getCurrentDate() == ""){
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
formattedDate = df.format(c.getTime());
currentDateTextView.setText(formattedDate);
}else {
formattedDate = session.getCurrentDate();
currentDateTextView.setText(formattedDate);
}
// Fetch data for current date.
mGetJobCardJsonData = new GetJobCardJsonData(formattedDate, session.getDealershipID());
mGetJobCardJsonData.getjobcards();
mGetJobCardJsonData.setOnCarcalDownloadListener(new CarcalDownloadListener() {
#Override
public void OnDownloadCompleted() {
List<JobCard> mJobCards = mGetJobCardJsonData.getJobCardList();
mJobCardRecyclerViewAdapter = new JobCardRecyclerViewAdapter(mJobCards, JobCardCalenderActivity.this);
mRecyclerView.setAdapter(mJobCardRecyclerViewAdapter);
}
});
}
Can anyone help on what i am doing wrong that is freezing the UI. It was working fine before and has started to freeze the UI suddenly.
I was able to fix the issue, the problem was not with Async task but with the layout. I accidently wrapped the recycler view with scroll view. which was causing the UI to freeze. Looks weird that a scroll view caused the whole UI thread to freeze. but here is my solution
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<view
android:id="#+id/jobCardRecyclerView"
class="android.support.v7.widget.RecyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/jobCardHeader"
android:scrollbars="vertical"></view>
</ScrollView>
Changed it to
<view
android:id="#+id/jobCardRecyclerView"
class="android.support.v7.widget.RecyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/jobCardHeader"
android:scrollbars="vertical"></view>
hope it will be helpful for others facing same problem.

Categories

Resources