Upload image from android studio to Wcf Service - java

i am sending image from android studio to wcf service both codes are correct and when i click on sendToServer button the app gone crashed. i don't know what is wrong with my code.
here is the code for MainActivity.java
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
private static final int CAMERA_REQUEST = 1888;
private int PICK_IMAGE_REQUEST = 1;
public PlaceholderFragment() {
}
private final static String SERVICE_URI = "http://localhost:24895/WcfAndroidImageService/WcfAndroidImageService.svc";
ImageView imageView = null;
byte[] photoasbytearray = null;
Photo ph = null;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
//getting photo as byte array
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100,stream);
photoasbytearray = stream.toByteArray();
//give a name of the image here as date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HHmm");
String currentDateandTime = sdf.format(new Date());
ph = new Photo();
String encodedImage = Base64.encodeToString(photoasbytearray,Base64.DEFAULT);
ph.photoasBase64=encodedImage;
ph.photoName= currentDateandTime+".png";
}
}
private void SendToServer(Photo ph2) throws UnsupportedEncodingException {
// TODO Auto-generated method stub
HttpPost httpPost = new HttpPost(SERVICE_URI+"LoadPhoto");
httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");
HttpClient httpClient = new DefaultHttpClient(getHttpParameterObj(17000,17000));
// Building the JSON object.
com.google.gson.Gson gson = new GsonBuilder().disableHtmlEscaping().create();
String json = gson.toJson(ph2);
StringEntity entity = new StringEntity(json,"UTF_8");
Log.d("WebInvoke", "data : " + json);
httpPost.setEntity(entity);
// Making the call.
HttpResponse response = null;
try
{
response = httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
Log.d("Exception",e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Getting data from the response to see if it was a success.
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()
));
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("IO_Exception",e.toString());
}
String jsonResultStr = null;
try {
jsonResultStr = reader.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("WebInvoke", "donnen deger : " + jsonResultStr);
}
private HttpParams getHttpParameterObj(int timeOutConnection, int timeOutSocket)
{
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
HttpConnectionParams.setConnectionTimeout(httpParameters, timeOutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
HttpConnectionParams.setSoTimeout(httpParameters, timeOutSocket);
return httpParameters;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_photo, container,
false);
imageView = (ImageView)rootView.findViewById(R.id.imageView1);
Button btnOpenCam = (Button) rootView.findViewById(R.id.btnOpenCam);
Button btnSendServer = (Button) rootView.findViewById(R.id.btnSendServer);
Button btnOpenImage = (Button)rootView.findViewById(R.id.openImage);
btnOpenCam.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Start camera activity here
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
});
btnOpenImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
});
btnSendServer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
SendToServer(ph);
// Toast.makeText(getActivity(),"Image Sent to Server!", Toast.LENGTH_SHORT).show();
//Toast.makeText(getActivity(),"Server got the image!", Toast.LENGTH_SHORT).show();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
return rootView;
}
}
}
here is Photo.java
package com.example.haier.leafclassification;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class Photo {
public String photoasBase64;
public String photoName ;
}
On the server end here is IWcfAndroidImageService.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace WcfAndroidPhotoServis
{
[ServiceContract]
public interface IWcfAndroidImageService
{
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
// BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "LoadPhoto")]
string LoadPhoto(Photo photo);
}
}
And here is the WcfAndroidImageService.svc file code
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using WcfAndroidPhotoServis.Helper;
namespace WcfAndroidPhotoServis
{
public class WcfAndroidImageService : IWcfAndroidImageService
{
public string LoadPhoto(Photo photo)
{
//get photofolder path
string photofolderName = "LoadedPhotos";
string photopath = "";
photopath = System.Web.Hosting.HostingEnvironment.MapPath("~/"+photofolderName);
//convert byte array to image
Image _photo = ImageHelper.Base64ToImage(photo.photoasBase64);
photopath = photopath + "/" + photo.photoName;
//save photo to folder
_photo.Save(photopath);
//chech if photo saved correctlly into folder
bool result = File.Exists(photopath);
// string result = "Server got the image!";
return result.ToString();
}
}
[DataContract]
public class Photo
{
//device id
[DataMember]
public string photoasBase64 { get; set; }
[DataMember]
public string photoName { get; set; }
}
}
here is the message i got in the main activity log
W/System.err: org.apache.http.conn.HttpHostConnectException: Connection to http://localhost:24895 refused
and here are the three line numbers main activity log is showing
java.lang.NullPointerException: Attempt to invoke interface method 'org.apache.http.HttpEntity org.apache.http.HttpResponse.getEntity()' on a null object reference
at com.example.haier.leafclassification.MainActivity$PlaceholderFragment.SendToServer(MainActivity.java:378)
at com.example.haier.leafclassification.MainActivity$PlaceholderFragment.access$100(MainActivity.java:293)
at com.example.haier.leafclassification.MainActivity$PlaceholderFragment$3.onClick(MainActivity.java:463)
and these lines have the following code
Line 378: reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()
Line 293: public static class PlaceholderFragment extends Fragment {
Line 463: SendToServer(ph);

Related

Endless RecyclerView with ProgressBar in Search activity

I am new at android. I have a search activity which searches for a query using async task, i want to implement endless/infinite scrolling when user reaches bottom. I want to add a parameter startrow to async task which will then be passed on to the server telling which row to begin.
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVFish;
private AdapterFish mAdapter;
private LinearLayoutManager mLayoutManager;
private String searchQuery;
SearchView searchView = null;
private String query;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// adds item to action bar
getMenuInflater().inflate(R.menu.search_main, menu);
// Get Search item from action bar and Get Search service
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager) MainActivity.this.getSystemService(Context.SEARCH_SERVICE);
if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName()));
searchView.setIconified(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
Every time when you press search button on keypad an Activity is recreated which in turn calls this function
#Override
protected void onNewIntent(Intent intent) {
// Get search query and create object of class AsyncFetch
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
query = intent.getStringExtra(SearchManager.QUERY);
if (searchView != null) {
searchView.clearFocus();
}
new AsyncFetch(query).execute();
}
}
class AsyncFetch which will fetch data from the server
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
HttpURLConnection conn;
URL url = null;
String searchQuery;
public AsyncFetch(String searchQuery){
this.searchQuery=searchQuery;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// URL address wherephp file resides
url = new URL("http://someurl/json/search.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput to true as we send and recieve data
conn.setDoInput(true);
conn.setDoOutput(true);
// add parameter to our above url
Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return("Connection error");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
List<DataFish> data=new ArrayList<>();
pdLoading.dismiss();
if(result.equals("no rows")) {
Toast.makeText(MainActivity.this, "No Results found for entered query", Toast.LENGTH_LONG).show();
}else{
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataFish fishData = new DataFish();
try {
fishData.fileName = URLDecoder.decode(json_data.getString("file"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
fishData.linkName = json_data.getString("link");
fishData.reg_date = json_data.getString("reg_date");
fishData.fileSize = json_data.getString("filesize");
data.add(fishData);
}
// Setup and Handover data to recyclerview
mRVFish = (RecyclerView) findViewById(R.id.fishPriceList);
mAdapter = new AdapterFish(MainActivity.this, data);
// mRVFish.setLayoutManager(new LinearLayoutManager(MainActivity.this));
mLayoutManager = new LinearLayoutManager(MainActivity.this);
mRVFish.setLayoutManager(mLayoutManager);
mRVFish.setAdapter(mAdapter);
} catch (JSONException e) {
// You to understand what actually error is and handle it appropriately
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
Add EndlessScrollListener to recyclerView from link:
https://gist.github.com/zfdang/38ae655a4fc401c99789#file-endlessrecycleronscrolllistener-java
override onLoadMore method and call your AsyncFetch Task.

Image taken from camera cannot display in image view android 5.0, but working in android 4.4

This is my activity code, when click on capture picture button, it will load camera from your phone. after i take a picture with camera, the picture will show at the imageView. Then i will click upload image picture button to upload my picture to server. Here the problem i faced, the code works well on all android version 4.4 and below, when i test this code with android 5.0, the picture taken from camera wasn't show on the imageView. I had tried many solution and yet keep fail. Can anyone help me with this? thank you.
Activity code
public class TestUpload extends Activity implements OnItemSelectedListener {
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final String IMAGE_DIRECTORY_NAME = "Hello camera";
private Uri fileUri;
private ImageView imgPreview;
private Button btnCapturePicture, btnUploadImage;
private EditText itemname;
private EditText description;
private EditText price;
private EditText contact;
private String randNum, uname;
Random random = new Random();
private static final String _CHAR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
private static final int RANDOM_STR_LENGTH = 12;
private Spinner spinCat, spinLoc;
private String [] Category = {"IT Gadgets","Men Fashion","Women Fashion","Beauty","Sports","Cars and Motors","Furnitures","Music Instrument","Books","Property","Photography","Games and Toys","kids and Baby","Others"};
private String [] Location = {"Kuala Lumpur","Melacca","Johor","Selangor","Kelantan","Kedah","Negeri Sembilan",
"Pahang","Perak","Perlis","Penang","Sabah","Sarawak","Terengganu"};
private static final String TAG_SUCCESS = "success";
JSONParser2 jsonParser2 = new JSONParser2();
private static String url_create_image = "http://gemini888.tk/GP_trade_api_v2/image_connect/create_product.php";
private SweetAlertDialog pDialog;
long totalSize = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upload_test);
ActionBar ab = getActionBar();
ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#96ead7")));
ab.setDisplayHomeAsUpEnabled(true);
imgPreview = (ImageView) findViewById(R.id.imgPreview);
btnCapturePicture = (Button) findViewById(R.id.btn_camera);
btnUploadImage = (Button) findViewById(R.id.btn_upload);
itemname = (EditText) findViewById(R.id.input_upload_item_name);
description = (EditText) findViewById(R.id.input_item_desc);
price = (EditText) findViewById(R.id.upload_input_item_price);
contact = (EditText) findViewById(R.id.input_contact);
spinCat = (Spinner) findViewById(R.id.spin_category);
spinLoc = (Spinner) findViewById(R.id.spin_location);
ArrayAdapter<String> adapter_Category = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_item, Category);
ArrayAdapter<String> adapter_Location = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_item, Location);
adapter_Category.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter_Location.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinCat.setAdapter(adapter_Category);
spinLoc.setAdapter(adapter_Location);
spinCat.setOnItemSelectedListener(this);
spinLoc.setOnItemSelectedListener(this);
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
HashMap<String, String> user = new HashMap<String, String>();
user = db.getUserDetails();
uname = user.get("uname");
//timeStamp = new SimpleDateFormat ("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
randNum = getRandomString();
//capture image button click event
btnCapturePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//capture image
captureImage();
}
});
btnUploadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//uploading the file to server
new UploadFileToServer().execute();
}
});
}
//capturing Camera image will lunch camera app request image capture
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
//Start image capture intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
//Receiving activity result method will be called after closing the camera
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//if the result i capture image
if(requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if(resultCode == RESULT_OK) {
//success capture image, display it on imageview
previewCapturedImage();
} else if (resultCode == RESULT_CANCELED) {
//user cancel image capture
Toast.makeText(getApplicationContext(), "User cancelled image capture", Toast.LENGTH_SHORT).show();
} else {
//failed to capture image
Toast.makeText(getApplicationContext(), "Sorry, failed to capture image", Toast.LENGTH_SHORT).show();
}
}
}
//Display image from a path to imageview
private void previewCapturedImage() {
imgPreview.setVisibility(View.VISIBLE);
//bitmap factory
BitmapFactory.Options options = new BitmapFactory.Options();
//downsize image as it throws Outofmemory execption for larger images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(), options);
imgPreview.setImageBitmap(bitmap);
}
//store the file url as it will be null after returning from camera app
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//save file url in bundle as it will be null on screen orientation change
outState.putParcelable("file_uri", fileUri);
}
//restore the fileUri again
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
//get the Urifile
fileUri = savedInstanceState.getParcelable("file_uri");
}
//create file Uri to store image
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
//returning image
private File getOutputMediaFile(int type) {
//External sdcard location
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), UserFunctions.IMAGE_DIRECTORY_NAME);
//create the storage directory if it does not exist
if(!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Failed create" + UserFunctions.IMAGE_DIRECTORY_NAME + "directory");
return null;
}
}
//Create a media file name
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator + uname + randNum + ".jpg");
} else {
return null;
}
return mediaFile;
}
//upload image to server
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new SweetAlertDialog(TestUpload.this, SweetAlertDialog.PROGRESS_TYPE);
pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
pDialog.setTitleText("Picture uploading, please wait..");
//pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(Void...params) {
String iname = itemname.getText().toString();
String des = description.getText().toString();
String iprice = price.getText().toString();
String icontact = contact.getText().toString();
String cat = spinCat.getSelectedItem().toString();
String loc = spinLoc.getSelectedItem().toString();
List<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("name", iname));
param.add(new BasicNameValuePair("description", des));
param.add(new BasicNameValuePair("price", iprice));
param.add(new BasicNameValuePair("username", uname));
param.add(new BasicNameValuePair("category", cat));
param.add(new BasicNameValuePair("location", loc));
param.add(new BasicNameValuePair("timestamp", randNum));
param.add(new BasicNameValuePair("contact", icontact));
JSONObject json = jsonParser2.makeHttpRequest(url_create_image,
"POST", param);
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Log.d("Create Response", "success");
} else {
// failed to create product
Toast.makeText(getApplicationContext(),"failed",Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return uploadFile();
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
super.onPostExecute(result);
}
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(UserFunctions.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
setProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(fileUri.getPath());
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
// Extra parameters if you want to pass to server
entity.addPart("website",
new StringBody("http://gemini888.tk"));
entity.addPart("email", new StringBody("thegemini888#gmail.com"));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
public String getRandomString() {
StringBuffer randStr = new StringBuffer();
for (int i =0; i<RANDOM_STR_LENGTH; i++) {
int number = getRandomNumber();
char ch = _CHAR.charAt(number);
randStr.append(ch);
}
return randStr.toString();
}
private int getRandomNumber() {
int randomInt = 0;
randomInt = random.nextInt(_CHAR.length());
if (randomInt - 1 == -1) {
return randomInt;
} else {
return randomInt - 1;
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
spinCat.setSelection(position);
String CatList = (String) spinCat.getSelectedItem();
CatList.toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; go home
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
in captureImage() method try this.
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
try {
intent.putExtra("return-data", true);
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
//Start image capture intent
}
//first of all create a directory to store your captured Images
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/PGallery");
if (!myDir.exists()) {
myDir.mkdirs();
}
//Give name to your captured Image
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss",java.util.Locale.getDefault());
Date date = new Date();
String sDate = formatter.format(date);
imageName = "PRAVA"+sDate+".jpg";
try {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
filePath = new File(myDir,imageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(filePath));
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
catch (ActivityNotFoundException e) {
String errorMessage = "Whoops - your device doesn't support capturing images!";
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
On Actvity Result:
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
ImagePath = filePath.getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(ImagePath, bitmapOptions);
ImageView mImageView = (ImageView) findViewById(R.id.ivCamreaPic);
mImageView.setImageBitmap(bitmap);
}

Transform Android Activity Class to Android Fragment Class Code [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Here is the code that Im trying to convert my code from activity extended class to fragment but it seems like it is difficult.
May i ask assistance to someone?
Activity Java Code
#SuppressLint("NewApi")
public class FileComplaintActivity extends Activity {
private Button buttonSubmit;
private EditText editTextName;
private EditText editTextComplaint;
//private EditText editTextPlateNo;
Bitmap thumbnail;
File pic;
private EditText editTextEmail;
private EditText editTextNo;
private Button button1;
private final static String PREFERENCE_USER = "user";
private Spinner spinnerComplaintType;
private Spinner spinnerVehicleType;
private EditText editTextBodyNo;
private EditText editTextPlateNo;
private EditText editTextLocation;
private EditText editTextDate;
private EditText editTextComplaintDetails;
private String username;
private String complaintType;
private String vehicletype;
private String date;
private int year;
private int month;
private int day;
static final int DATE_PICKER_ID = 1111;
private static final int CAMERA_PIC_REQUEST = 1111;
private ImageView imageViewPhotoReport;
String imageString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_report);
initViews();
}
private void initViews() {
// TODO Auto-generated method stub
buttonSubmit = (Button)findViewById(R.id.buttonSubmit);
username= getUsername();
editTextBodyNo = (EditText)findViewById(R.id.editTextBodyNo);
editTextPlateNo = (EditText)findViewById(R.id.editTextPlate);
editTextLocation = (EditText)findViewById(R.id.editTextLocation);
editTextDate = (EditText)findViewById(R.id.editTextDate);
editTextComplaintDetails = (EditText)findViewById(R.id.editTextComplaintDetails);
button1 = (Button)findViewById(R.id.button1);
spinnerComplaintType = (Spinner)findViewById(R.id.spinnerComplaintType);
ArrayAdapter<CharSequence> adapterComplaint = ArrayAdapter.createFromResource(getBaseContext(), R.array.complaintType, android.R.layout.simple_list_item_1);
spinnerComplaintType.setAdapter(adapterComplaint);
spinnerComplaintType.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
complaintType = parent.getItemAtPosition(position).toString();
// Toast.makeText(getApplicationContext(), complaintType, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
spinnerVehicleType = (Spinner)findViewById(R.id.spinnerVehicleType);
ArrayAdapter<CharSequence> adapterVehicle = ArrayAdapter.createFromResource(getBaseContext(), R.array.vehicleType, android.R.layout.simple_list_item_1);
spinnerVehicleType.setAdapter(adapterVehicle);
spinnerVehicleType.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
vehicletype = parent.getItemAtPosition(position).toString();
// Toast.makeText(getApplicationContext(), vehicletype, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
editTextDate.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(year)
.append("-")
.append(month + 1)
.append("-").append(day));
imageViewPhotoReport=(ImageView)findViewById(R.id.imageViewPhotoReport);
}
public void buttonDateClicked(View view){
showDialog(DATE_PICKER_ID);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_PICKER_ID:
// open datepicker dialog.
// set date picker for current date
// add pickerListener listner to date picker
return new DatePickerDialog(this, pickerListener, year, month,day);
}
return null;
}
private DatePickerDialog.OnDateSetListener pickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
#Override
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// Show selected date
editTextDate.setText(new StringBuilder()
.append(year)
.append("-")
.append(month + 1)
.append("-").append(day)
);
}
};
#SuppressLint("UnlocalizedSms")
public void buttonClickSubmit(View view){
Toast.makeText(getApplicationContext(), "Message Sent", Toast.LENGTH_SHORT).show();
SmsManager smsManager = SmsManager.getDefault();
// smsManager.sendTextMessage("+639177260573", null, "HAHAHAH", null, null);
smsManager.sendTextMessage("+639178866281", null, "Name: "+editTextName.getText().toString()+" Plate No: "+ editTextPlateNo.getText().toString() + " Complaint: "+editTextComplaint.getText().toString(), null, null);
//finishAffinity();
//Toast.makeText(getApplicationContext(), editTextNo.getText().toString(), Toast.LENGTH_SHORT).show();
}
private String getUsername() {
SharedPreferences preference = getSharedPreferences(PREFERENCE_USER,
MODE_PRIVATE);
username = preference.getString("username", "");
if (!username.isEmpty()) {
return username;
}
return "";
}
public void buttonClickEmail(View view){
String to = "olannataniel#yahoo.com";
String subject = editTextName.getText().toString();
String message = editTextComplaint.getText().toString();
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[]{ to});
//email.putExtra(Intent.EXTRA_CC, new String[]{ to});
//email.putExtra(Intent.EXTRA_BCC, new String[]{to});
email.putExtra(Intent.EXTRA_SUBJECT, subject);
email.putExtra(Intent.EXTRA_TEXT, message);
//need this to prompts email client only
email.setType("message/rfc822");
startActivity(Intent.createChooser(email, "Choose an Email client :"));
}
public void buttonSendClick(View view){
final Calendar c = Calendar.getInstance();
int yyyy = c.get(Calendar.YEAR);
int mm = c.get(Calendar.MONTH);
int dd = c.get(Calendar.DAY_OF_MONTH);
date = yyyy + "-" + (mm+1) + "-" + dd;
SendComplaintTask task = new SendComplaintTask();
try {
String status = task.execute().get();
Toast.makeText(this, status, Toast.LENGTH_SHORT).show();
// Intent intent = new Intent(this, LoginActivity.class);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
public class SendComplaintTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... arg0) {
String url = getResources().getString(R.string.url_addComplaint);
// Toast.makeText(getApplicationContext(), yyyy + "-" + mm + "-" + dd, Toast.LENGTH_SHORT).show();
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
ArrayList<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
pairList.add(new BasicNameValuePair("complaintType", complaintType));
pairList.add(new BasicNameValuePair("vehicleType", vehicletype));
pairList.add(new BasicNameValuePair("bodyNo", editTextBodyNo
.getText().toString()));
pairList.add(new BasicNameValuePair("plateNo", editTextPlateNo
.getText().toString()));
pairList.add(new BasicNameValuePair("complaintLocation", editTextLocation
.getText().toString()));
pairList.add(new BasicNameValuePair("complaintDate", editTextDate
.getText().toString()));
pairList.add(new BasicNameValuePair("complaintDetails", editTextComplaintDetails
.getText().toString()));
pairList.add(new BasicNameValuePair("complaintImage", imageString));
pairList.add(new BasicNameValuePair("dateFiled", date.toString()));
pairList.add(new BasicNameValuePair("username", username));
try {
post.setEntity(new UrlEncodedFormEntity(pairList));
HttpResponse response = client.execute(post);
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
String line = "";
String json = "";
while ((line = reader.readLine()) != null) {
json += line + System.getProperty("line.separator");
}
Log.i("asdf", json);
JSONObject jsonObject = new JSONObject(json);
String status = jsonObject.getString("status");
return status;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
public void buttonTakePhoto(View view){
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST) {
//2
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
imageViewPhotoReport.setImageBitmap(thumbnail);
imageViewPhotoReport.setVisibility(1);
//3
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//4
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
//5
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
imageString = Base64.encodeToString(bytes.toByteArray(),
Base64.NO_WRAP);
// Toast.makeText(getApplicationContext(), "TEST: " + imageString, Toast.LENGTH_SHORT).show();
editTextComplaintDetails.setText(imageString);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.create_report, menu);
return true;
}
}
Here is my initial Fragment Code
public class WhatsHotFragment extends Fragment {
public WhatsHotFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_whats_hot, container, false);
return rootView;
}
}
what i want to ask is that how can i implement initViews() function in Activity to Fragment
So
Buttom button
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_whats_hot, container, false);
return rootView;
}
Override onActivityCreated
Then
button = (Button)getView()findViewById(R.id.buttonSubmit);
// similarly for other views
There is no harm in initializing view in onActivitedCreated.
You can also initialize your view's in onCreateView
Buttom button
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_whats_hot, container, false);
button = button = (Button)getView()findViewById(R.id.buttonSubmit);
// similarly for other views
return rootView;
}
For more info
http://developer.android.com/guide/components/fragments.html
Fragment lifecycle is a bit different than Activity lifecycle.
Although a fragment has the onCreate(), onStart(), onResume() etc. methods which are called along with the same method of the activity, we set up a fragment differently.
A fragment inflates its user interface in its onCreateView() method, which returns a View.
After that, we do further setup in onViewCreated(). (E.g. set up onClickListeners, etc.).
Of course you can find this all here: http://developer.android.com/guide/components/fragments.html
Edit:
Although it's possible to setup subviews in onActivityCreated(), it's better to do the setup in onViewCreated(), because onViewCreated() was intended to do this, so it conforms better to the docs.

Fragment Tabs not Appearing

In my program i am showing multilevel Listview, but whenever i am calling another Activity then Fragment Tabs are not appearing.
I am using this great tutorial: http://www.androidbegin.com/tutorial/android-actionbarsherlock-viewpager-tabs-tutorial/
See below Images, 1st Level ListView:
2nd Level ListView:
ListCategoryFragment.xml:-
public class ListCategoryFragment extends SherlockFragment implements OnItemClickListener {
ListView lview3;
ListCategoryAdapter adapter;
private ArrayList<Object> itemList;
private ItemBean bean;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Get the view from fragmenttab1.xml
View view = inflater.inflate(R.layout.fragment_category_tab, container, false);
prepareArrayList();
lview3 = (ListView) view.findViewById(R.id.listView1);
adapter = new ListCategoryAdapter(getActivity(), itemList);
lview3.setAdapter(adapter);
lview3.setOnItemClickListener(this);
return view;
}
private static final int categoryFirst = 0;
private static final int categorySecond = 1;
private static final int categoryThird = 2;
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
// Set up different intents based on the item clicked:
switch (position)
{
case categoryFirst:
Intent intent1 = new Intent(getActivity(), ListItemActivity.class);
intent1.putExtra("category", "Category - 1");
startActivity(intent1);
break;
case categorySecond:
Intent intent2 = new Intent(getActivity(), ListItemActivity.class);
intent2.putExtra("category", "Category - 2");
startActivity(intent2);
break;
case categoryThird:
Intent intent3 = new Intent(getActivity(), ListItemActivity.class);
intent3.putExtra("category", "Category - 3");
startActivity(intent3);
break;
default:
break;
}
}
public void prepareArrayList()
{
itemList = new ArrayList<Object>();
AddObjectToList("Category - 1");
AddObjectToList("Category - 2");
AddObjectToList("Category - 3");
}
// Add one item into the Array List
public void AddObjectToList(String title)
{
bean = new ItemBean();
bean.setTitle(title);
itemList.add(bean);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
setUserVisibleHint(true);
}
}
ListItemActivity.java:-
public class ListItemActivity extends SherlockFragmentActivity {
static String URL = "http://www.site.url/tone.json";
static String KEY_CATEGORY = "item";
static final String KEY_TITLE = "title";
ListView list;
ListItemAdapter adapter;
/** Called when the activity is first created. */
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_item_list);
final ArrayList<HashMap<String, String>> itemsList = new ArrayList<HashMap<String, String>>();
list = (ListView) findViewById(R.id.listView1);
adapter = new ListItemAdapter(this, itemsList);
list.setAdapter(adapter);
Bundle bdl = getIntent().getExtras();
KEY_CATEGORY = bdl.getString("category");
if (isNetworkAvailable()) {
new MyAsyncTask().execute();
} else {
AlertDialog alertDialog = new AlertDialog.Builder(ListItemActivity.this).create();
alertDialog.setMessage("The Internet connection appears to be offline.");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
private Intent getDefaultShareIntent(){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "SUBJECT");
intent.putExtra(Intent.EXTRA_TEXT, "TEXT");
startActivity(Intent.createChooser(intent, "Share via"));
return intent;
}
/** The event listener for the Up navigation selection */
#Override
public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
switch(item.getItemId())
{
case android.R.id.home:
finish();
break;
case R.id.menu_item_share:
getDefaultShareIntent();
break;
}
return true;
}
private boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
return (info != null);
}
class MyAsyncTask extends
AsyncTask<String, Integer, ArrayList<HashMap<String, String>>> {
private ProgressDialog progressDialog = new ProgressDialog(
ListItemActivity.this);
#Override
protected void onPreExecute() {
progressDialog.setMessage("Loading, Please wait.....");
progressDialog.show();
}
final ArrayList<HashMap<String, String>> itemsList = new ArrayList<HashMap<String, String>>();
#Override
protected ArrayList<HashMap<String, String>> doInBackground(
String... params) {
HttpClient client = new DefaultHttpClient();
// Perform a GET request for a JSON list
HttpUriRequest request = new HttpGet(URL);
// Get the response that sends back
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Convert this response into a readable string
String jsonString = null;
try {
jsonString = StreamUtils.convertToString(response.getEntity()
.getContent());
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Create a JSON object that we can use from the String
JSONObject json = null;
try {
json = new JSONObject(jsonString);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
JSONArray jsonArray = json.getJSONArray(KEY_CATEGORY);
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonObject = jsonArray.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put(KEY_TITLE, jsonObject.getString(KEY_TITLE));
itemsList.add(map);
}
return itemsList;
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
list = (ListView) findViewById(R.id.listView1);
adapter = new ListItemAdapter(ListItemActivity.this, itemsList);
list.setAdapter(adapter);
TextView lblTitle = (TextView) findViewById(R.id.text);
lblTitle.setText(KEY_CATEGORY);
this.progressDialog.dismiss();
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> map = itemsList.get(position);
Intent in = new Intent(ListItemActivity.this, ListItemDetailActivity.class);
in.putExtra(KEY_TITLE, map.get(KEY_TITLE));
startActivity(in);
}
});
}
}
}
This is the normal behavior because you are moving from the Fragment Activity to a normal Activity. But only your first activity has the tabs.
The correct way of doing this is to remove the intents and the new activities. Instead it should be replaced with fragments itself.
For example, in the list item click, stop calling the Intent to the new fragment activity, and replace it calling a fragment itself.
There will be only one Activity and that will be the one which is holding the tabs and all others should be fragments. You just need to replace the fragments from within the same activity.

Android Animation Sequence Loads Slowly - Appears To Hang [duplicate]

I have an android Animation which loads a series of sequential dots (publishProgress) however there is a 10+ second delay before they start because I have them as a part of my AsyncTask which loads once the data is processing (technically - the two should be related - but it visually causes there to be a delay) how can I call this animation when the class first starts instead? I need to remove this visual animation delay.
SOURCE:
public class UpdateActivity extends Activity implements OnClickListener {
private TelephonyManager tm;
AlertDialog mConfirmAlert = null;
NetworkTask task;
ImageView image, text;
AlertDialog mErrorAlert = null;
public static ArrayList<String> NameArr = new ArrayList<String>();
public static ArrayList<String> ValueArr = new ArrayList<String>();
public static ArrayList<String> nameArr = new ArrayList<String>();
public static ArrayList<String> ApnArr = new ArrayList<String>();
public static ArrayList<String> mmscArr = new ArrayList<String>();
public static ArrayList<String> mmsportArr = new ArrayList<String>();
public static ArrayList<String> mmsproxyArr = new ArrayList<String>();
public static ArrayList<String> portArr = new ArrayList<String>();
public static ArrayList<String> proxyArr = new ArrayList<String>();
private ImageView mProgressImageview1;
private ImageView mProgressImageview2;
private ImageView mProgressImageview3;
private ImageView mProgressImageview4;
private ImageView mProgressImageview5;
private Button mUpdateButton = null;
private Button mAssistUpdateButton = null;
private Button mAssistInstrButton = null;
private TextView mReadAgainButton = null;
public static int count;
public AnimationDrawable mTextAnimation = null;
private Button assist_update_btn = null;
TextView mUpdatetext;
public static InputStream stream = null;
int version;
public static BigInteger iD1, iD2, mdN1, mdN2;
BigInteger[] id, mdnId;
public static String ICCID, MDN;
private int mInstructionNumber = 0;
public static String caR, result;
private static final String LOG_TAG = "DataSettings";
public static final String Base_URL = "https://apps.example.com/REST/phoneSettings";
public static XmlParserHandlerFinal handler;
public static int TotalSteps = 8;
public FileInputStream fis;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// instance for xml parser class
handler = new XmlParserHandlerFinal();
handler.setContext(this.getBaseContext());
tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
int networkType = tm.getNetworkType();
int phoneType = tm.getPhoneType();
version = android.os.Build.VERSION.SDK_INT;
// to get MDN(MCC+MNC) of the provider of the SIM and ICCID (Serial
// number of the SIM)
// and to check for the Carrier type
getImpVariablesForQuery();
task = new NetworkTask();
if (phoneType == TelephonyManager.PHONE_TYPE_CDMA
|| (phoneType != TelephonyManager.PHONE_TYPE_GSM
&& networkType != TelephonyManager.NETWORK_TYPE_GPRS
&& networkType != TelephonyManager.NETWORK_TYPE_EDGE
&& networkType != TelephonyManager.NETWORK_TYPE_HSDPA
&& networkType != TelephonyManager.NETWORK_TYPE_HSPA
&& networkType != TelephonyManager.NETWORK_TYPE_HSPAP
&& networkType != TelephonyManager.NETWORK_TYPE_HSUPA
&& networkType != TelephonyManager.NETWORK_TYPE_UMTS && networkType != TelephonyManager.NETWORK_TYPE_LTE)) {
// If the phone type is CDMA or
// the phone phone type is not GSM and the network type is none of
// the network types indicated in the statement
// Display incompatibility message
showAlert(getString(R.string.incomp_sm_dialog));
// Network type is looked because some tablets have no phone type.
// We rely on network type in such cases
} else if (!(tm.getSimState() == TelephonyManager.SIM_STATE_ABSENT
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_tmo)) || (tm
.getSimOperator()).equals(getString(R.string.numeric_att)))) {
// if SIM is present and is NOT a T-Mo or ATT network SIM,
// display Error message alert indicating to use SM SIM
showAlert(getString(R.string.insert_sm_dialog));
}// No SIM or SIM with T-Mo & ATT MNC MCC present
else if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
// Device has T-Mo or ATT network SIM card MCC and MNC correctly
// populated
TotalSteps = 6;
setContentView(R.layout.updating);
// AsyncTask to call the web service
task = new NetworkTask();
task.execute("");
}
}
public void onClick(View v) {
if (v == mUpdateButton) {
// Update button for versions lower than ICS is selected
onClickMethod(v);
Intent i = new Intent(this, ConfigFinalActivity.class);
startActivity(i);
finish();
} else
if (v.getId() == R.id.assist_update_btn) {
// Update button for ICS and up is selected
// Get the TextView in the Assist Update UI
TextView tv = (TextView) findViewById(R.id.apn_app_text_cta2);
String text = "";
CharSequence styledText = text;
switch (mInstructionNumber) {
case 0:
// Retrieve the instruction string resource corresponding the
// 2nd set of instructions
text = String.format(getString(R.string.apn_app_text_instr),
TotalSteps);
styledText = Html.fromHtml(text);
// Update the TextView with the correct set of instructions
tv.setText(styledText);
// Increment instruction number so the correct instructions
// string resource can be retrieve the next time the update
// button is pressed
mInstructionNumber++;
break;
case 1:
text = getString(R.string.apn_app_text_instr2);
styledText = Html.fromHtml(text);
tv.setText(styledText);
// Increment instruction number so the correct instructions
// string resource can be retrieve the next time the update
// button is pressed
mInstructionNumber++;
break;
case 2:
// Final set of instructions-Change to the corresponding layout
setContentView(R.layout.assist_instructions);
String assistUpdateInstr = String.format(
getString(R.string.apn_app_text_instr3), TotalSteps);
styledText = Html.fromHtml(assistUpdateInstr);
TextView assistInstrText = (TextView) findViewById(R.id.updated_text);
assistInstrText.setText(styledText);
mAssistInstrButton = (Button) findViewById(R.id.assist_instr_btn);
mReadAgainButton = (TextView) findViewById(R.id.read_again_btn);
mAssistInstrButton.setOnClickListener(this);
mReadAgainButton.setOnClickListener(this);
}
} else if (v == mAssistInstrButton) {
// "LET'S DO THIS" Button in final instructions screen for ICS and
// up is selected
// Create ConfigActivity Intent
Intent i = new Intent(this, ConfigFinalActivity.class);
// Invoke ConfigActivity Intent to start the assisted update
startActivity(i);
startActivity(new Intent(Settings.ACTION_APN_SETTINGS));
} else if (v == mReadAgainButton) {
// go back to 1st set of instructions if read again is selected
mInstructionNumber = 0;
setContentView(R.layout.assist_update);
String assistUpdate = getString(R.string.apn_app_text_cta2);
CharSequence styledText = Html.fromHtml(assistUpdate);
TextView assistText = (TextView) findViewById(R.id.apn_app_text_cta2);
assistText.setText(styledText);
mAssistUpdateButton = (Button) findViewById(R.id.assist_update_btn);
mAssistUpdateButton.setOnClickListener(this);
}
}
public void onClickMethod(View v) {
mUpdateButton = (Button) findViewById(R.drawable.btn_update_active_hdpi);
}
private void showAlert(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
UpdateActivity.this.finish();
}
});
mConfirmAlert = builder.create();
mConfirmAlert.show();
}
private void getImpVariablesForQuery() {
long d = 1234;
BigInteger divisor = BigInteger.valueOf(d);
// to get MDN
// MDN = tm.getLine1Number();
MDN = "3055861092";
if (MDN.equals("")) {
mdN1 = null;
mdN2 = null;
} else {
Log.d("MDN", MDN);
BigInteger bInt = new BigInteger(MDN);
mdnId = bInt.divideAndRemainder(divisor);
// to retrieve ICCID number of the SIM
mdN1 = mdnId[1];
System.out.println("MDN%1234 = " + mdN1);
mdN2 = mdnId[0];
System.out.println("MDN/1234 = " + mdN2);
}
ICCID = tm.getSimSerialNumber();
if (ICCID.equals("")) {
iD1 = null;
iD2 = null;
} else {
Log.d("ICCID", ICCID);
BigInteger bInteger = new BigInteger(ICCID);
id = bInteger.divideAndRemainder(divisor);
iD1 = id[1];
System.out.println("ICCID%1234 = " + iD1);
iD2 = id[0];
System.out.println("ICCID/1234 = " + iD2);
}
// Check for the Carrier Type
if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))) {
caR = "TMO";
} else if ((tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
caR = "ATT";
}
}
// method to save the ArrayLists from parser
public static void setArrayList() {
nameArr = handler.getnameArr();
ApnArr = handler.getApnArr();
mmscArr = handler.getMMSCArr();
mmsproxyArr = handler.getMmscProxyArr();
mmsportArr = handler.getMmsPortArr();
proxyArr = handler.getProxyArr();
portArr = handler.getPortArr();
count = handler.getCount();
result = handler.getResult();
}
public ArrayList<String> getnameArr() {
return nameArr;
}
public ArrayList<String> getApnArr() {
return ApnArr;
}
public ArrayList<String> getMMSCArr() {
return mmscArr;
}
public ArrayList<String> getMmscProxyArr() {
return mmsproxyArr;
}
public ArrayList<String> getMmsPortArr() {
return mmsportArr;
}
public int getCount() {
return count;
}
public ArrayList<String> getProxyArr() {
return proxyArr;
}
public ArrayList<String> getPortArr() {
return portArr;
}
// AsyncTask to call web service
public class NetworkTask extends AsyncTask<String, Integer, InputStream> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//
}
#Override
protected InputStream doInBackground(String... params) {
int result = 0;
{
Log.i("url...", Base_URL);
try {
stream = getQueryResults(Base_URL);
} catch (SocketTimeoutException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SSLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SAXException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// The code below plays a ST Promo animation
// prior to displaying update success or failure message
for (int incr = 0; incr < 2; incr++) {
// Sleep for 1/2 second
// Invoke UI to change updating text to show 1 dot
// And Increasing the level to reduce the amount of clipping
// and
// slowly reveals the hand image
publishProgress(R.drawable.loading_full,
R.drawable.loading_empty, R.drawable.loading_empty,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_empty,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_empty, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_empty);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}
publishProgress(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full);
// Sleep for 1/2 second
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}
}
return stream;
}
}
/*
* Sends a query to server and gets back the parsed results in a bundle
* urlQueryString - URL for calling the webservice
*/
protected synchronized InputStream getQueryResults(String urlQueryString)
throws IOException, SAXException, SSLException,
SocketTimeoutException, Exception {
try {
// HttpsURLConnection https = null;
String uri = urlQueryString;
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
BasicNameValuePair mdn1, mdn2,id1,id2;
if (MDN.equals("")) {
mdn1 = new BasicNameValuePair("mdn1", null);
mdn2 = new BasicNameValuePair("mdn2", null);
} else {
mdn1 = new BasicNameValuePair("mdn1", mdN1.toString());
mdn2 = new BasicNameValuePair("mdn2", mdN2.toString());
}
BasicNameValuePair car = new BasicNameValuePair("car", caR);
if (ICCID.equals("")) {
id1 = new BasicNameValuePair("id1", null);
id2 = new BasicNameValuePair("id2", null);
} else {
id1 = new BasicNameValuePair("id1",
iD1.toString());
id2 = new BasicNameValuePair("id2",
iD2.toString());
}
nameValuePairs.add(mdn1);
nameValuePairs.add(mdn2);
nameValuePairs.add(car);
nameValuePairs.add(id1);
nameValuePairs.add(id2);
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(
nameValuePairs, "ISO-8859-1");
KeyStore trustStore = KeyStore.getInstance(KeyStore
.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(
params, registry);
HttpClient httpClient = new DefaultHttpClient(ccm, params);
params = httpClient.getParams();
HttpClientParams.setRedirecting(params, true);
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader("Authorization",
getB64Auth("nmundru", "abc123"));
httpPost.setHeader("Content-Type", "text/plain; charset=utf-8");
Log.v("httpPost", httpPost.toString());
httpPost.setEntity(urlEncodedFormEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println("response...." + httpResponse.toString());
Log.v("response...", httpResponse.toString());
stream = httpResponse.getEntity().getContent();
// save the InputStream in a file
try {
FileOutputStream fOut = openFileOutput("settings.xml",
Context.MODE_WORLD_READABLE);
DataInputStream in = new DataInputStream(stream);
BufferedReader br = new BufferedReader(
new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println(strLine); //to print the response
// in logcat
fOut.write(strLine.getBytes());
}
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
fis = openFileInput("settings.xml");
} catch (Exception e) {
Log.e(LOG_TAG, e.toString());
// tryagain();
} finally {
// https.disconnect();
}
return stream;
}
private String getB64Auth(String login, String pass) {
String source = login + ":" + pass;
String ret = "Basic "
+ Base64.encodeToString(source.getBytes(), Base64.URL_SAFE
| Base64.NO_WRAP);
return ret;
}
#Override
protected void onPostExecute(InputStream stream) {
super.onPostExecute(stream);
// This method is called to parse the response and save the
// ArrayLists
success();
}
public void success() {
// to parse the response
try {
handler.getQueryResponse(fis);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// set method to save the ArryaLists from the parser
setArrayList();
Intent i = new Intent(UpdateActivity.this, ConfigFinalActivity.class);
startActivity(i);
finish();
}
// Framework UI thread method corresponding to publishProgress call in
// worker thread
protected void onProgressUpdate(Integer... progress) {
// Call function to update image view
setProgressImgView(progress[0], progress[1], progress[2],
progress[3], progress[4]);
}
}
private void setProgressImgView(Integer imgViewId1, Integer imgViewId2,
Integer imgViewId3, Integer imgViewId4, Integer imgViewId5) {
// update image view with the updating dots
// Reset view layout in case orientation while updating
setContentView(R.layout.updating);
mProgressImageview1 = (ImageView) findViewById(R.id.loading_empty1);
mProgressImageview2 = (ImageView) findViewById(R.id.loading_empty2);
mProgressImageview3 = (ImageView) findViewById(R.id.loading_empty3);
mProgressImageview4 = (ImageView) findViewById(R.id.loading_empty4);
mProgressImageview5 = (ImageView) findViewById(R.id.loading_empty5);
mProgressImageview1.setImageResource(imgViewId1);
mProgressImageview2.setImageResource(imgViewId2);
mProgressImageview3.setImageResource(imgViewId3);
mProgressImageview4.setImageResource(imgViewId4);
mProgressImageview5.setImageResource(imgViewId5);
}
#Override
protected void onRestart() {
super.onRestart();
if (mErrorAlert != null)
mErrorAlert.dismiss();
}
public void tryagain() {
// Displaying final layout after failure of pre-ICS automatic settings
// update
setContentView(R.layout.tryagain);
String tryAgainText = "";
CharSequence styledTryAgainText;
tryAgainText = String.format(getString(R.string.tryagain_text1),
TotalSteps);
styledTryAgainText = Html.fromHtml(tryAgainText);
TextView tryAgain1 = (TextView) findViewById(R.id.tryagain_text1);
tryAgain1.setText(styledTryAgainText);
tryAgainText = String.format(getString(R.string.tryagain_text2),
TotalSteps);
styledTryAgainText = Html.fromHtml(tryAgainText);
TextView tryAgain2 = (TextView) findViewById(R.id.tryagain_text2);
tryAgain2.setText(styledTryAgainText);
tryAgainText = String.format(getString(R.string.tryagain_text3),
TotalSteps);
styledTryAgainText = Html.fromHtml(tryAgainText);
TextView tryAgain3 = (TextView) findViewById(R.id.tryagain_text3);
tryAgain3.setText(styledTryAgainText);
}
private void assistUpdate() {
// Displaying final layout after pre-ICS automatic settings update
setContentView(R.layout.assist_update);
assist_update_btn = (Button) findViewById(R.id.assist_update_btn);
assist_update_btn.setOnClickListener((OnClickListener) this);
}
public void success() {
// to parse the response
try {
handler.getQueryResponse(fis);
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// set method to save the ArryaLists from the parser
setArrayList();
Intent i = new Intent(this, ConfigFinalActivity.class);
startActivity(i);
finish();
}
public String getResult() {
return result;
}
}
You can use onPreExecute() and onPostExecute() methods from the AsyncTask to set the loading before/ remove it after the work is done.
try:
protected void onPreExecute() {
setProgressImgView(R.drawable.loading_full,
R.drawable.loading_empty, R.drawable.loading_empty,
R.drawable.loading_empty, R.drawable.loading_empty);
}
protected void onPostExecute(InputStream stream) {
setProgressImgView(R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full,
R.drawable.loading_full, R.drawable.loading_full);
// This method is called to parse the response and save the
// ArrayLists
success();
}

Categories

Resources