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());
}
}
Related
In the system when I select msg that msg by default display on spinner.I require this project those select item display only spinner.If I change item not show previous select item display on spinner.
list.java
Spinner sp1;
TextView entry;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
sp1=(Spinner) findViewById(R.id.spinner1);
entry = (TextView)findViewById(R.id.TextView123);
getFilesnames();
}
private void getFilesnames() {
// TODO Auto-generated method stub
String[] filenames=getApplicationContext().fileList();
List<String> list=new ArrayList<String>();
for(int i=0;i<filenames.length;i++){
list.add(filenames[i]);
}
ArrayAdapter<String> filenameAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list);
sp1.setAdapter(filenameAdapter);
}
public void onClick(View v) {
// TODO Auto-generated method stub
String selectFile = String.valueOf(sp1.getSelectedItem());
openFile(selectFile);
}
private void openFile(String selectFile) {
// TODO Auto-generated method stub
String value = "";
FileInputStream fis;
try {
fis = openFileInput(selectFile);
byte[] input = new byte[fis.available()];
while(fis.read(input) != -1){
value += new String(input);
}
fis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
entry.setText(value);
}
Check whether list has value after binding like following code:
private void getFilesnames() {
// TODO Auto-generated method stub
String[] filenames=getApplicationContext().fileList();
List<String> list=new ArrayList<String>();
for(int i=0;i<filenames.length;i++){
list.add(filenames[i]);
}
/***
check here list has value or not
***/
if(list.size() <= 0) {
list.add("You string.....");
}
ArrayAdapter<String> filenameAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list);
sp1.setAdapter(filenameAdapter);
}
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();
}
I am missing something very crucial but I can't quite see what. Can someone please assist. It's probably something really silly that I have missed but I cannot initiate my onItemClick.
onCreate....
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
actu_ip = intent.getStringExtra(IPEntry.ACTUALSMARTIP);
setContentView(R.layout.act_ipcontrol);
mainListView = (ListView) findViewById( R.id.mainListView );
String[] options = new String[] { "All in to 1", "Spare"};
ArrayList<String> optionsList = new ArrayList<String>();
optionsList.addAll( Arrays.asList(options) );
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, optionsList);
mainListView.setAdapter( listAdapter );
try {
Toast.makeText(IPControl.this, "Please wait...Connecting...", Toast.LENGTH_SHORT).show();
new AsyncAction().execute();
} catch(Exception e) {
e.printStackTrace();
}
}
private class AsyncAction extends AsyncTask<String, Void, String> {
protected String doInBackground(String... args) {
try {
InetAddress serverAddr = InetAddress.getByName(actu_ip);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream());
BufferedWriter bw = new BufferedWriter(osw);
out = new PrintWriter(bw, true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (! in .ready());
readBuffer();
out.println("root\r\n");
while (! in .ready());
readBuffer();
out.println("root\r\n");
while (! in .ready());
readBuffer();
out.println("[verbose,off\r\n");
while (! in .ready());
String msg = "";
while ( in .ready()) {
msg = msg + (char) in .read();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;//returns what you want to pass to the onPostExecute()
}
protected void onPostExecute(String result) {
Toast.makeText(IPControl.this, "Connected", Toast.LENGTH_SHORT).show();
//results the data returned from doInbackground
IPControl.this.data = result;
}
}
private String readBuffer() throws IOException {
String msg = "";
while(in.ready()) {
msg = msg + (char)in.read();
}
//System.out.print(msg);
if(msg.indexOf("SNX_COM> ") != -1) return msg.substring(0, msg.indexOf("SNX_COM> "));
else if(msg.indexOf("SCX_COM> ") != -1) return msg.substring(0, msg.indexOf("SCX_COM> "));
else return msg;
}
}
What I want to initiate...
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
try {
new AsyncAction1().execute();
} catch(Exception e) {
e.printStackTrace();
}
}
private class AsyncAction1 extends AsyncTask<String, Void, String> {
protected String doInBackground(String... args) {
try {
out.println("[c,l#,i1,o*\r\n");
//System.out.print("root\r\n");
while(! in .ready());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;//returns what you want to pass to the onPostExecute()
}
protected void onPostExecute(String result) {
//results the data returned from doInbackground
Toast.makeText(IPControl.this, "Command Sent", Toast.LENGTH_SHORT).show();
IPControl.this.data = result;
}
}
I haven't seen setOnItemClickListener method for listview in your code. Have you implemented it?
Try following
mainListView.setAdapter( listAdapter );
mainListView.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
try {
new AsyncAction1().execute();
}catch(Exception e) {
e.printStackTrace();
}
});
Thanks for all your help, I fixed my problem.
I just wasn't doing things in the correct order.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
actu_ip = intent.getStringExtra(IPEntry.ACTUALSMARTIP);
setContentView(R.layout.act_ipcontrol);
mainListView = (ListView) findViewById( R.id.mainListView );
final String[] options = new String[] { "All in to 1", "Spare"};
ArrayList<String> optionsList = new ArrayList<String>();
optionsList.addAll( Arrays.asList(options) );
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, optionsList);
mainListView.setAdapter( listAdapter );
mainListView.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
try {
if(pos == 0) {
AsyncAction1 a = new AsyncAction1();
a.setCmd("[c,l#,i1,o*\r\n");
a.execute();
}
} catch(Exception e) {
e.printStackTrace();
}
}
});
Then....
private class AsyncAction1 extends AsyncTask<String, Void, String> {
String cmd;
public void setCmd(String c) {
cmd = c;
}
protected String doInBackground(String... args) {
try {
out.println(cmd);
//System.out.print("root\r\n");
while(! in .ready());
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;//returns what you want to pass to the onPostExecute()
}
protected void onPostExecute(String result) {
//results the data returned from doInbackground
Toast.makeText(IPControl.this, "Command Sent", Toast.LENGTH_SHORT).show();
IPControl.this.data = result;
}
}
}
i have a written a code to send a text file by converting it into string and sending it into a web service. Please can someone tell me other available methods for sending the string as stream to Web Service.
public class MainActivity extends Activity {
Button b1;
String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
File upfile=new File("sdcard/text/testfile.txt");
try {
FileInputStream fin=new FileInputStream(upfile);
byte[] buffer= new byte[(int)upfile.length()];
new DataInputStream(fin).readFully(buffer);
fin.close();
s=new String(buffer,"UTF-8");
System.out.print(buffer);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, s, 20).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
try this.
public void mReadJsonData() {
try {
File f = new File("sdcard/text/testfile.txt");
FileInputStream is = new FileInputStream(f);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String text = new String(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Use this code to read the data from file and get it into string and do your process ahead according to your need--
File upfile=new File("sdcard/text/testfile.txt");
try {
final BufferedReader reader = new BufferedReader(new FileReader(upfile));
String encoded = "";
try {
String line;
while ((line = reader.readLine()) != null) {
encoded += line;
}
}
finally {
reader.close();
}
System.out.print(encoded);
}
catch (final Exception e) {
}
I'm trying to read a random line from a file. My code doesn't have error, just comes up with a force close as soon as it runs in the emulator and I can't work out why!
public class filereader extends Activity {
TextView t = (TextView)findViewById(R.id.text);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
Scanner s = new Scanner(getResources().openRawResource(R.raw.lev1)); {
try {
while (s.hasNext()) {
String word = s.next();
t.setText(word);
}
}
finally {
s.close();
}
}
}
TextView t = (TextView)findViewById(R.id.text);
you can not run findViewById until the setContentView has been called:
TextView t = null; #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = (TextView)findViewById(R.id.text);
}
please be sure that you declare text inside the main.xml
do this
BufferedReader myReader = null;
try
{
fIn = openFileInput("customer_number.txt");
myReader = new BufferedReader(new InputStreamReader(fIn));
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
String aDataRow = "";
//String aBuffer = "";
try
{
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
// TO display Whole Data of File
Toast.makeText(getBaseContext(),aBuffer,Toast.LENGTH_SHORT).show();
}
// To display Last Entered Number
Toast.makeText(getBaseContext(),last_number,Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public void readfromfile(){
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
String s +=readstring;
}
InputRead.close();
Toast.makeText(getBaseContext(), s,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
It will read the text file named "mytext.txt" string by string and store it by appending it to string variable s. So the variable "s" contains final string taken from file.