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

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

Related

Upload image from android studio to Wcf Service

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

Debugging Android App communicating with Servlet on real device

So the scenario is I am trying to debug a simple application on my real device.I am using eclipse to make the application.
Now my application is communicating with a servlet which is on Server and application is running very smoothly in genymotion emulator(not using the emulator provided by eclipse). But when I try to run it in my device it is working perfectly till one activity class,but application is crashing on second activity.
So, after so many searches I am posting this question here. Hope I can find out any solution for this.
This is my Second Activity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.success);
Intent objIntent = getIntent();
s2 = objIntent.getStringExtra("repname");
findViewsById();
submit.setOnClickListener(this);
}
private void findViewsById() {
submit = (Button) findViewById(R.id.submit);
headerText = (TextView) findViewById(R.id.tv1);
headerText.setVisibility(View.INVISIBLE);
submit2 = (Button) findViewById(R.id.secondSubmit);
submit2.setVisibility(View.INVISIBLE);
t1= (TextView) findViewById(R.id.tvexample1);
t2= (TextView) findViewById(R.id.tvexample2);
submit2.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
//DO SOMETHING! {RUN SOME FUNCTION ... DO CHECKS... ETC}
lviewAdapter.clear();
lviewAdapter.notifyDataSetChanged();
Calendar cal = Calendar.getInstance();
System.out.println("what is from calendar"+cal);
Date currentLocalTime = cal.getTime();
//System.out.println("what is from CurrentLocalTime"+currentLocalTime);
DateFormat date = new SimpleDateFormat("yyyy-MM-dd");
date.setTimeZone(TimeZone.getTimeZone("GMT"));
//System.out.println("what is from date"+date);
String localTime = date.format(currentLocalTime);
//localTime = "2014-08-26";
System.out.println("and result is == " + localTime);
pb.setVisibility(View.VISIBLE);
new MyAsyncTask().execute(localTime,s2);
}
});
pb=(ProgressBar)findViewById(R.id.progressBar1);
pb.setVisibility(View.GONE);
c=this;
}
public void onClick(View view) {
Log.d("1:", "in the onclick");
Calendar cal = Calendar.getInstance();
System.out.println("what is from calendar"+cal);
Date currentLocalTime = cal.getTime();
//System.out.println("what is from CurrentLocalTime"+currentLocalTime);
DateFormat date = new SimpleDateFormat("yyyy-MM-dd");
date.setTimeZone(TimeZone.getTimeZone("GMT"));
//System.out.println("what is from date"+date);
String localTime = date.format(currentLocalTime);
//localTime = "2014-08-26";
System.out.println("and result is == " + localTime);
pb.setVisibility(View.VISIBLE);
new MyAsyncTask().execute(localTime,s2);
}
// #Override
// public void onBackPressed() {
// Log.d("CDA", "onBackPressed Called");
// Intent setIntent = new Intent(Intent.ACTION_MAIN);
// setIntent.addCategory(Intent.CATEGORY_HOME);
// setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// startActivity(setIntent);
// }
private class MyAsyncTask extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Log.d("tag1","in do in ");
String s=postData(params);
Log.d("tag2","in do in SSS ");
//Printing this 5 th
Log.d("what is s",s);
return s;
}
protected void onPostExecute(String result){
Log.d("on post ","on post execute");
pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(),"Appointment Displayed", Toast.LENGTH_SHORT).show();
//Log.d("tag",result);
init(result);
submit.setVisibility(View.GONE);
headerText.setVisibility(View.VISIBLE);
submit2.setVisibility(View.VISIBLE);
}
}
protected void onProgressUpdate(Integer... progress){
pb.setProgress(progress[0]);
}
public String postData(String valueIWantToSend[]) {
String origresponseText="";
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("CurrentDate",valueIWantToSend[0]));
nameValuePairs.add(new BasicNameValuePair("repname", valueIWantToSend[1]));
System.out.println("CurrentDate"+valueIWantToSend[0]);
System.out.println("username"+valueIWantToSend[1]);
exampleString1= valueIWantToSend[0];
exampleString2= valueIWantToSend[1];
HttpClient httpclient = new DefaultHttpClient();
HttpParams params = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),10000000);
//httppost = new HttpPost("http://192.168.56.1:8080/First/Hello");
httppost = new HttpPost("http://203.199.134.131:8080/First/Hello");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
/* execute */
HttpResponse response = httpclient.execute(httppost);
System.out.println("response from servlet"+response.toString());
origresponseText=readContent(response);
Log.d("response", origresponseText);
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
}
catch (IOException e) {
// TODO Auto-generated catch block
}
//removing unwated "" and other special symbols from response
String responseText = origresponseText.substring(1,origresponseText.length() -2 );
Log.d("Response tag", responseText);
return responseText;
}
// }
String readContent(HttpResponse response)
{
String text = "";
InputStream in =null;
try {
in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
//Log.d("", line);
sb.append(line + "\n");
//Printing this first
// Log.d("", line);
// Log.e("TAGpppp", ">>>>>PRINTING<<<<<");
// Log.e("TAGiiii", in.toString());
}
text = sb.toString();
Log.d("TEXT", text);
}
catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
in.close();
} catch (Exception ex) {
}
}
return text;
}
#SuppressWarnings("deprecation")
public void init(String result) {
System.out.println(result);
t1.setText(exampleString1);
t2.setText(exampleString2);
String response= result + "}";
System.out.println(response);
try {
JSONObject jsonArray = new JSONObject(response);
System.out.println("1:"+jsonArray);
//ArrayList obj1 = new ArrayList();
JSONArray obj1 = jsonArray.getJSONArray("get");
System.out.println("1:"+obj1);
for (int i = 0; i < obj1.length(); i++) {
System.out.println("Length of array"+obj1.length());
JSONObject results = obj1.getJSONObject(i);
System.out.println("2:"+results);
String pcode= results.getString("ProspCustCode");
System.out.println("Prospect code"+pcode);
String date= results.getString("FollowUpDate");
System.out.println("FollowUpDate"+date);
String time= results.getString("FollowUpTime");
System.out.println("FollowUpTime"+time);
String status= results.getString("Status");
System.out.println("Status"+status);
String ftype= results.getString("FollowUpType");
System.out.println("FollowUpType"+ftype);
String ntime= results.getString("NextFollowUpTime");
System.out.println("NextFollowUpTime"+ntime);
String cname= results.getString("ContactPerson");
System.out.println("ContactPerson"+cname);
String desig= results.getString("Designation");
System.out.println("Designation"+desig);
String com= results.getString("Comments");
System.out.println("Comments"+com);
String spoke= results.getString("SpokenTo");
System.out.println("SpokenTo"+spoke);
insertdata(pcode,date,time,status,ftype,ntime,cname,desig,com,spoke);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void insertdata(String PROSPCUSTCODE, String DATE, String TIME,
String STATUS, String FOLLOWUPTYPE, String NEXTFOLLOWUPTIME, String NAME,
String DESIGNATION, String COMMENTS, String SPOKENTO) {
HashMap<String, String> queryValues = new HashMap<String, String>();
queryValues.put("ProspCustCode", PROSPCUSTCODE);
queryValues.put("Date", DATE);
queryValues.put("Time", TIME);
queryValues.put("Status", STATUS);
queryValues.put("FollowUpType", FOLLOWUPTYPE);
queryValues.put("NextFollowUpTime", NEXTFOLLOWUPTIME);
queryValues.put("Name", NAME);
queryValues.put("Designation", DESIGNATION);
queryValues.put("Comments", COMMENTS);
queryValues.put("SpokenTo", SPOKENTO);
controller.insertDeails(queryValues);
//this.callHomeActivity(view);
DBController dbHelper = new DBController(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor cursor = newDB.rawQuery("SELECT * FROM TempFollowUpDetails", null);
if (cursor != null ) {
if (cursor.moveToFirst()) {
do {
System.out.println(cursor.getColumnIndex("ProspCustCode"));
//String ProspCustCode = c.getString(c.getColumnIndex("ProsCustCode"));
String Date = cursor.getString(cursor.getColumnIndex("Date"));
String Time = cursor.getString(cursor.getColumnIndex("Time"));
String Status = cursor.getString(cursor.getColumnIndex("Status"));
String NextFollowUpTime = cursor.getString(cursor.getColumnIndex("NextFollowUpTime"));
Name = cursor.getString(cursor.getColumnIndex("Name"));
System.out.println(cursor.getString(cursor.getColumnIndex("Name")));
String Designation = cursor.getString(cursor.getColumnIndex("Designation"));
String Comments = cursor.getString(cursor.getColumnIndex("Comments"));
String SpokenTo = cursor.getString(cursor.getColumnIndex("SpokenTo"));
String Id = cursor.getString(cursor.getColumnIndex("Id"));
//ProspCustCodeArray.add(ProspCustCode);
DateArray.add(Date);
TimeArray.add(Time);
StatusArray.add(Status);
NextFollowUpTimeArray.add(NextFollowUpTime);
NameArray.add(Name);
DesignationArray.add(Designation);
CommentsArray.add(Comments);
SpokenToArray.add(SpokenTo);
IdArray.add(Id);
}while (cursor.moveToNext());
}
displaylist(IdArray,NameArray);
}
System.out.println("Elements of name array"+NameArray);
System.out.println("Elements of name array"+DateArray);
System.out.println("Elements of name array"+TimeArray);
System.out.println("Elements of name array"+DesignationArray);
System.out.println("Elements of name array"+CommentsArray);
System.out.println("Elements of name array"+IdArray);
//............. For normal listview
}
private void displaylist(ArrayList<String> idArray2,
ArrayList<String> nameArray2) {
// TODO Auto-generated method stub
listView = (ListView) findViewById(R.id.listViewAnimals);
lviewAdapter = new ListCustomAdapter(this, idArray2, nameArray2);
System.out.println("adapter => "+lviewAdapter.getCount());
listView.setAdapter(this.lviewAdapter);
controller.deleteDetails(null);
//... start appointments details activity to show the details on item click listener
this.listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View viewClicked, int position, long id) {
TextView tv1 =(TextView)viewClicked.findViewById(R.id.lblListItem);
Intent intent = new Intent(Success.this, AppointmentDetails.class);
intent.putExtra("name", tv1.getText().toString());
startActivity(intent);
}
}); }
}
This is what my Log cat shows when asynctask is satrting after button click:
D/1:(15416): in the onclick
I/System.out(15416): what is from calendarjava.util.GregorianCalendar[time=1409392501700,areFieldsSet=true,lenient=true,zone=Asia/Calcutta,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2014,MONTH=7,WEEK_OF_YEAR=35,WEEK_OF_MONTH=5,DAY_OF_MONTH=30,DAY_OF_YEAR=242,DAY_OF_WEEK=7,DAY_OF_WEEK_IN_MONTH=5,AM_PM=1,HOUR=3,HOUR_OF_DAY=15,MINUTE=25,SECOND=1,MILLISECOND=700,ZONE_OFFSET=19800000,DST_OFFSET=0]
I/System.out(15416): and result is == 2014-08-26
D/tag1(15416): in do in
I/System.out(15416): CurrentDate2014-08-26
I/System.out(15416): usernameaditi
I/System.out(15416): [socket][1] connection /203.199.134.131:8080;LocalPort=36598(10000000)
I/System.out(15416): [CDS]connect[/203.199.134.131:8080] tm:10000 D/Posix(15416): [Posix_connect Debug]Process com.example.simplehttpgetservlet :8080
I/System.out(22364): [socket][/192.168.2.73:45340] connected
I/System.out(15416): [CDS]rx timeout:0
W/System.err(15416): rto value is too small
I/System.out(15416): >doSendRequest
I/System.out(15416): <doSendRequest
I/System.out(15416): response from servletorg.apache.http.message.BasicHttpResponse#423611d8
If you use a real device you need to use the real IP of the server. Keep also in mind to open the required ports for your local network and connect your mobile with your local network via WiFi.
I'm not very familar with the secutity of servlets check also that you can connect to the server with a second computer too. (Depending on your configuration it is possible that you cannot access the server from outside of "localhost")

How can i get checked checkboxes values from checkbox when checkbox made programmatically in android

I am making check-boxes programmatically. and I want to get value of checked check-boxes when click on button... how can i do this....
I am getting value of checkboxes from database.
Here is my working code..
public class Loyaltyprogram extends Activity {
SessionManager session;
EditText mpv, discount;
Button save;
String finalresult, getFlag, statusEmp, accessName, emp_id, bus_id,
preferences, bus_type_id, emp_access_name, responseString, success,
name, id, pref, per_amout, percentage, datediff, dateNo, minpvalue , discountonit;
Toast tag;
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
ProgressDialog pDialog;
int a;
String[] idsplit, namesplit, prefsplit;
List<String> testArrayList;
LinearLayout llmain;
LinearLayout[] lLayout;
Integer count1 = 0;
Context mContext;
TextView tvo;
CheckBox cb;
StringBuffer result = new StringBuffer();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.loyaltyprogram);
tvo = (TextView) findViewById(R.id.tvother);
mpv = (EditText) findViewById(R.id.et_minpurchase);
discount = (EditText) findViewById(R.id.et_discount);
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
new Homedatanew().execute();
llmain = (LinearLayout) findViewById(R.id.linearLayoutMain);
} else {
Toast toast = Toast.makeText(getApplicationContext(),
"Check your internet connection", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
save = (Button) findViewById(R.id.button);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
minpvalue = mpv.getText().toString();
discountonit = discount.getText().toString();
for(int t = 0; t<idsplit.length; t++)
{
if(cb.isChecked())
{
System.out.println(idsplit[t]);
}
}
}
});
}
class Homedatanew extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Loyaltyprogram.this);
pDialog.setMessage("loading data..");
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://10.0.2.2/amardeep/android_api/checkbox.php");
try {
session = new SessionManager(getApplicationContext());
// get user data from session
HashMap<String, String> user = session.getUserDetails();
// id
bus_id = user.get(SessionManager.KEY_B_ID);
bus_type_id = user.get(SessionManager.KEY_B_TYPE_ID);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("bus_type_id",
"BT101"));
nameValuePairs.add(new BasicNameValuePair("bus_id", "B101"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
response.getStatusLine().getStatusCode();
HttpEntity getResponseEntity = response.getEntity();
responseString = EntityUtils.toString(getResponseEntity);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
return responseString;
}
#SuppressLint("NewApi")
protected void onPostExecute(String resultStr) {
try {
JSONObject json = new JSONObject(responseString);
JSONArray jArray = json.getJSONArray("customer");
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
success = json_data.getString("success");
id = json_data.getString("id");
name = json_data.getString("name");
pref = json_data.getString("pref");
per_amout = json_data.getString("per_amount");
percentage = json_data.getString("percentage");
datediff = json_data.getString("dateDiff");
dateNo = json_data.getString("dateNo");
if (percentage.equals("null")) {
percentage = "";
}
if (per_amout.equals("null")) {
per_amout = "";
}
if((datediff.equals("No"))&&(dateNo.equals("No")))
{
count1 = 1;
}
else if((datediff.equals("YES"))&&(dateNo.equals("No")))
{
count1 = 2;
}
else
{
count1 = 0;
}
idsplit = id.split(",");
a = idsplit.length;
namesplit = name.split(",");
prefsplit = pref.split(",");
testArrayList = new ArrayList<String>(
Arrays.asList(prefsplit));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (success.equals("1")) {
mpv.setText(per_amout);
discount.setText(percentage);
if ((count1.equals(1)) || (count1.equals(2))) {
mpv.setEnabled(true);
discount.setEnabled(true);
} else {
mpv.setEnabled(false);
discount.setEnabled(false);
save.setEnabled(false);
}
int b = (a / 5);
int c = (a % 5);
if (c != 0) {
b = b + 1;
}
lLayout = new LinearLayout[b];
for (int j = 0; j < b; j++) {
int x = 0;
x = x + (j * 5);
lLayout[j] = new LinearLayout(Loyaltyprogram.this);
lLayout[j].setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
lLayout[j].setOrientation(LinearLayout.VERTICAL);
llmain.addView(lLayout[j]);
for (int i = x; i < x + 5; i++) {
if (x > a) {
break;
} else {
if (testArrayList.contains(idsplit[i])) {
cb = new CheckBox(Loyaltyprogram.this);
cb.setText(namesplit[i] + (i + 1));
cb.setId(i + 1);
cb.setChecked(true);
cb.setTextColor(Color.BLACK);
cb.setTextSize(12f);
cb.setButtonDrawable(R.drawable.checkbox);
cb.setPadding(35, 5, 25, 5);
if (count1.equals(1)) {
cb.setEnabled(true);
} else {
cb.setEnabled(false);
}
lLayout[j].addView(cb);
} else {
cb = new CheckBox(Loyaltyprogram.this);
cb.setText(namesplit[i] + (i + 1));
cb.setId(i + 1);
cb.setTextColor(Color.BLACK);
cb.setTextSize(12f);
cb.setButtonDrawable(R.drawable.checkbox);
cb.setPadding(35, 5, 25, 5);
if (count1.equals(1)) {
cb.setEnabled(true);
} else {
cb.setEnabled(false);
}
lLayout[j].addView(cb);
}
}
}
}
} else {
Toast.makeText(getApplicationContext(), "data empty",
Toast.LENGTH_LONG).show();
mpv.setEnabled(true);
discount.setEnabled(true);
}
pDialog.dismiss();
}
}
}
Just do this inside the loop and if , else condition
cb.setTag(i+99); // set the tag values so that you can refer to them later.
cb.setOnCheckedChangeListener(handleCheck(cb)); // here pass the checkbox object.
Then this is handleCheck method
private OnCheckedChangeListener handleCheck (final CheckBox chk)
{
return new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(!isChecked){
Toast.makeText(getApplicationContext(), "You unchecked " + chk.getTag(),
Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "You checked " + chk.getTag(),
Toast.LENGTH_LONG).show();
}
}
};
}
Hope this gives you some idea. Happy coding :)

InsertAPN() Method Does Not Write APN Settings - Android 2.3.6

I have an android application which is supposed to write new APN settings to a device however every time I run the application the new APN settings do not appear to be written to the device (the APN settings are totally blank after execution) I belive this may have something to do with a problem with InsertAPN() [shown below] however I'm unable to determine the root cause of the issue.
P.S.
Any debugging tips/questions are greatly appreciated.
SOURCE SNIPPET:
/*
* Insert a new APN entry into the system APN table Require an apn name, and
* the apn address. More can be added. Return an id (_id) that is
* automatically generated for the new apn entry.
*/
public int InsertAPN() throws SecurityException {
int id = -1;
for (i = 0; i < count; i++) {
ContentValues values2 = new ContentValues();
// values2 = values1;
values2 = getValues();
ContentResolver resolver = getContentResolver();
Cursor c = null;
try {
Uri newRow = resolver.insert(APN_TABLE_URI, values2);
// System.out.println("values in insertAPN" + values1);
if (newRow != null) {
c = resolver.query(newRow, null, null, null, null);
Log.d(TAG, "Newly added APN:");
// TF Settings have been inserted
// Obtain the apn id
int idindex = c.getColumnIndex("_id");
c.moveToFirst();
id = c.getShort(idindex);
Log.d(TAG, "New ID: " + id
+ ": Inserting new APN succeeded!");
}
} catch (SQLException e) {
Log.d(TAG, e.getMessage());
}
if (c != null)
c.close();
}
return id;
}
FULL SOURCE:
public class ConfigFinalActivity extends Activity implements OnClickListener {
private static final String TAG = "ConfigActivity";
TelephonyManager tm;
AlertDialog mErrorAlert = null;
private Notification mNotification = null;
private Button mXButton = null;
private Button mAssistUpdateButton = null;
private Button mAssistInstrButton = null;
private Button mReadAgainButton = null;
private int mInstructionNumber = 0;
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>();
public static int count;
public static int TotalSteps = 8;
int i, g = 0, result = 0;
public static ContentValues Values = new ContentValues();
XmlParserHandlerFinal handler;
public static final Uri APN_TABLE_URI = Uri
.parse("content://telephony/carriers");
public static final String Base_URL = "https://wapgate.example.com/REST/phoneSettings";
public static InputStream stream = null;
UpdateActivity update;
public static String status, queryResult = "";
/** Called when the activity is first created. */
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int version = android.os.Build.VERSION.SDK_INT;
tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
update = new UpdateActivity();
handler = new XmlParserHandlerFinal();
handler.setContext(this.getBaseContext());
getArrayLists();
/*
* boolean deleted = deleteFile("settings.xml");if(deleted){
* Log.v("settings.xml","deleted"); }else
* Log.v("settings.xml","failed to delete the file");
*/
if (ApnArr.isEmpty() || mmscArr.isEmpty()) {
tryagain();
} else if (version < VERSION_CODES.ICE_CREAM_SANDWICH) {
// Update APN table
try {
result = updateTable();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}// Settings updated with this atomic call
catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (result != -1) {
status = "success";
} else {
status = "failure";
}
if (status.equals("success")) {
completeUpdate();
} else if (status.equals("failure")) {
tryagain();
// showAlert(getString(R.string.unchanged_dialog));
}
} else {// ICS and later versions
// Reduce number of steps to 6
TotalSteps = 6;
setContentView(R.layout.assist_instructions);
String assistUpdate = getString(R.string.instructions_1);
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);
}
}
private void getArrayLists() {
nameArr = update.getnameArr();
ApnArr = update.getApnArr();
mmscArr = update.getMMSCArr();
mmsproxyArr = update.getMmscProxyArr();
mmsportArr = update.getMmsPortArr();
proxyArr = update.getProxyArr();
portArr = update.getPortArr();
count = update.getCount();
queryResult = update.getResult();
}
public void onClick(View v) {
if (v == mAssistUpdateButton) {
// 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);
mAssistInstrButton.setOnClickListener(this);
}
} else if (v == mAssistInstrButton) {
// "LET'S DO THIS" Button in final instructions screen for ICS and
// up is selected
Values = getValues();
startActivity(new Intent(Settings.ACTION_APN_SETTINGS));
try {
showNotification();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finish();
} else if (v == mAssistInstrButton) {
startActivity(new Intent(Settings.ACTION_APN_SETTINGS));
try {
showNotification();
} catch (SAXException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ParserConfigurationException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
showNotification();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finish();
}
}
/*
* Insert a new APN entry into the system APN table Require an apn name, and
* the apn address. More can be added. Return an id (_id) that is
* automatically generated for the new apn entry.
*/
public int InsertAPN() throws SecurityException {
int id = -1;
for (i = 0; i < count; i++) {
ContentValues values2 = new ContentValues();
// values2 = values1;
values2 = getValues();
ContentResolver resolver = getContentResolver();
Cursor c = null;
try {
Uri newRow = resolver.insert(APN_TABLE_URI, values2);
// System.out.println("values in insertAPN" + values1);
if (newRow != null) {
c = resolver.query(newRow, null, null, null, null);
Log.d(TAG, "Newly added APN:");
// TF Settings have been inserted
// Obtain the apn id
int idindex = c.getColumnIndex("_id");
c.moveToFirst();
id = c.getShort(idindex);
Log.d(TAG, "New ID: " + id
+ ": Inserting new APN succeeded!");
}
} catch (SQLException e) {
Log.d(TAG, e.getMessage());
}
if (c != null)
c.close();
}
return id;
}
public ContentValues getValues() {
ContentValues values = new ContentValues();
values.put("name", nameArr.get(i));
values.put("apn", ApnArr.get(i));
values.put("mmsc", mmscArr.get(i));
//values.put("mmsproxy", mmsproxyArr.get(i));
//values.put("mmsport", mmsportArr.get(i));
// values.put("proxy", proxyArr.get(i));
values.put("port", portArr.get(i));
values.put("mcc", (getString(R.string.mcc)));
if ((tm.getSimOperator()).equals(getString(R.string.numeric_tmo))) {
values.put("numeric", getString(R.string.numeric_tmo));
values.put("mnc", (getString(R.string.mnc_tmo)));
} else if ((tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
values.put("numeric", getString(R.string.numeric_att));
values.put("mnc", (getString(R.string.mnc_att)));
}
return values;
}
/*
* Delete APN data where the indicated field has the values Entire table is
* deleted if both field and value are null
*/
private void DeleteAPNs(String field, String[] values)
throws SecurityException {
int c = 0;
c = getContentResolver().delete(APN_TABLE_URI, null, null);
if (c != 0) {
String s = "APNs Deleted:\n";
Log.d(TAG, s);
}
}
/*
* Return all column names stored in the string array
*/
private String getAllColumnNames(String[] columnNames) {
String s = "Column Names:\n";
for (String t : columnNames) {
s += t + ":\t";
}
return s + "\n";
}
/*
* Copy all data associated with the 1st record Cursor c. Return a
* ContentValues that contains all record data.
*/
private ContentValues copyRecordFields(Cursor c) {
if (c == null)
return null;
int row_cnt = c.getCount();
Log.d(TAG, "Total # of records: " + row_cnt);
ContentValues values = new ContentValues();//
if (c.moveToFirst()) {
String[] columnNames = c.getColumnNames();
Log.d(TAG, getAllColumnNames(columnNames));
String row = "";
for (String columnIndex : columnNames) {
int i = c.getColumnIndex(columnIndex);
row += c.getString(i) + ":\t";
// if (i>0)//Avoid copying the id field
// id to be auto-generated upon record insertion
values.put(columnIndex, c.getString(i));
}
row += "\n";
Log.d(TAG, row);
Log.d(TAG, "End Of Records");
}
return values;
}
// showAlert displays the text contained in message as an alert
public 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) {
ConfigFinalActivity.this.finish();
}
});
mErrorAlert = builder.create();
mErrorAlert.show();
}
// showErrorAlert displays an alert with layout and a title
private void showErrorAlert(int layoutRes, String title) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// Get the layout inflater
LayoutInflater inflater = ConfigFinalActivity.this.getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setTitle(title)
.setView(inflater.inflate(layoutRes, null))
.setPositiveButton(getString(R.string.assisted_button),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivity(new Intent(
Settings.ACTION_APN_SETTINGS));
try {
showNotification();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
mErrorAlert = builder.create();
mErrorAlert.show();
}
// showNotification starts the process of sending notifications to the bar
// to assist the user in updating the data settings on ICS and later
// versions of Android
#SuppressWarnings("deprecation")
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void showNotification() throws SAXException, ParserConfigurationException {
String field = getString(R.string.config_name_label);
String value = Values.get("name").toString();
int mId = 1;
String title = "1 of " + UpdateActivity.TotalSteps + " (Update "
+ field + ":)";
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notifications_icon)
.setContentTitle(title).setContentText(value);
Intent resultIntent = new Intent(this,
NotificationActivityForMultiProf.class);
resultIntent.putExtra(field, value);
PendingIntent resultPendingIntent = PendingIntent.getActivity(
getApplicationContext(), 0, resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotification = mBuilder.getNotification();
mNotification.flags |= Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(mId, mNotification);
finish();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
if (mNotification != null) {
outState.putString("NOTIFICATIONB", mNotification.toString());
}
}
#Override
protected void onRestart() {
super.onRestart();
if (mErrorAlert != null)
mErrorAlert.dismiss();
}
private int updateTable() throws IOException, SAXException,
ParserConfigurationException {
int insertResult = -1;
// returned value if table is not properly updated
try {
ContentValues values = new ContentValues();
// Query the carrier table for the current data settings
Cursor c = getContentResolver().query(APN_TABLE_URI, null,
"current=?", new String[] { "1" }, null);
values = copyRecordFields(c);
// Copy the settings into values
// Replace T-Mo/ATT Data settings if there is no SIM or
// NET10/T-Mo/ATT SIM is
// present
if (tm.getSimState() == TelephonyManager.SIM_STATE_ABSENT
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_tmo))) {
// delete all APNs before adding new APNs
DeleteAPNs("numeric=?",
new String[] { getString(R.string.numeric_tmo) });
// Insert Data Settings into Carrier table
insertResult = InsertAPN();
} else if (tm.getSimState() == TelephonyManager.SIM_STATE_ABSENT
|| (tm.getSimOperator())
.equals(getString(R.string.numeric_att))) {
// Delete all APNs before adding new APNs
DeleteAPNs("numeric=?",
new String[] { getString(R.string.numeric_att) });
// Insert Data Settings into Carrier table
insertResult = InsertAPN();
} else
// non NET10/ non T-Mo SIM/non ATT SIM
showAlert(getString(R.string.insert_sm_dialog));
} catch (SecurityException e) {
showErrorAlert(R.layout.assisted_setting,
getString(R.string.assited_title));
Log.d(TAG, e.getMessage());
}
return insertResult;
}
private void completeUpdate() {
// Displaying final layout after pre-ICS automatic settings update
setContentView(R.layout.completion);
TextView mCompleted = (TextView) findViewById(R.id.done_text);
String mDoneText = String.format(getString(R.string.done_text));
CharSequence styledText = Html.fromHtml(mDoneText);
mCompleted.setText(styledText);
mXButton = (Button) findViewById(R.id.x_button);
mXButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
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);
}
// This function return a cursor to the table holding the
// the APN configurations (Carrier table)
public Cursor getConfigTableCursor() {
return getContentResolver()
.query(APN_TABLE_URI, null, null, null, null);
}
}
You can no longer programatically change APN settings on Android 4.0 and up. So if you're debugging on Android 4.0 or higher, that is where your issue is.

An error connecting to Android Spinner

I am working on an Android app where I have a Spinner, and on the base of which item I choose, the app will read in text file number 1 or number 2, etc... I have written a code, but when I run it on my device, it says that "The application has stopped unexpectedly".
Here is my code:
public class MainActivity extends Activity implements OnClickListener, OnItemSelectedListener {
Spinner spinner;
String textSource = "";
TextView textMsg;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textMsg = (TextView) findViewById(R.id.textmsg);
spinner=(Spinner) findViewById(R.id.spinner1);
List<String> list = new ArrayList<String>();
list.add("list 1");
list.add("list 2");
list.add("list 3");
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
URL textUrl;
String stringText = "";
try {
textUrl = new URL(textSource);
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(textUrl.openStream(), "ISO-8859-1"));
//ISO-8859-1
String StringBuffer;
//String stringText = "";
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
textMsg.setText(stringText);
//textMsg.setText(string123);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
textMsg.setText(e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
textMsg.setText(e.toString());
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int pos,
long arg3) {
// TODO Auto-generated method stub
String Text = parent.getSelectedItem().toString();
if(Text.equals("list 1")) {
textSource = "path/to/textfile 1";
}
else if(Text.equals("list 2")){
textSource = "path/to/textfile 2";
}
else {
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
How should I solve this problem?
Thanks for helping
I would suggest you to use
String Text = spinner.getSelectedItem().toString();
instead of
String Text = parent.getSelectedItem().toString();
So that it becomes :
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int pos,
long arg3) {
String Text = spinner.getSelectedItem().toString();
if(Text.equals("list 1")) {
textSource = "path/to/textfile 1";
}
else if(Text.equals("list 2")){
textSource = "path/to/textfile 2";
}
else {
}
// then put your URL code here as follows
URL textUrl;
String stringText = "";
try {
textUrl = new URL(textSource);
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(textUrl.openStream(), "ISO-8859-1"));
//ISO-8859-1
String StringBuffer;
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
textMsg.setText(stringText);
//textMsg.setText(string123);
} catch (MalformedURLException e) {
e.printStackTrace();
textMsg.setText(e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
textMsg.setText(e.toString());
}
}
Since you are calling textUrl = new URL(textSource); inside oncreate() method textSource will be always " ". Better create a method and pass the new textSource value based on onItemSelected .
Sample for Your reference: By Default Link1 will be passed
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int pos,
long arg3) {
String Text = parent.getSelectedItem().toString();
if (Text.equals("list 1")) {
Method("path/to/textfile 1");
} else if (Text.equals("list 2")) {
Method("path/to/textfile 2");
} else {
}
// TODO Auto-generated method stub
}
Method :
public void Method(String textSource) {
URL textUrl;
String stringText = "";
try {
textUrl = new URL(textSource);
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(textUrl.openStream(), "ISO-8859-1"));
// ISO-8859-1
String StringBuffer;
// String stringText = "";
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
textMsg.setText(stringText);
// textMsg.setText(string123);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
textMsg.setText(e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
textMsg.setText(e.toString());
}
}

Categories

Resources