I am trying to make an app which uses FTP and changes the filename to a combination of 2 EditTexts. to properly upload it i am uploading it inside a 'asynctask' ,this is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
EditText week_text = (EditText) findViewById(R.id.week_edit);
EditText pagina_text = (EditText) findViewById(R.id.pagina_edit);
String week = "w" + week_text.getText().toString() + "_";
String pagina = "p" + pagina_text.getText().toString() + ".jpg";
Button foto_keuze = (Button)findViewById(R.id.foto_keuze_button);
Button upload_button = (Button)findViewById(R.id.upload_button);
Typeface Impact = Typeface.createFromAsset(getAssets(), "fonts/Impact.ttf");
foto_keuze.setTypeface(Impact);
upload_button.setTypeface(Impact);
targetImage = (ImageView)findViewById(R.id.imageView);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
public void upload_klik (View view) {
EditText week_text = (EditText) findViewById(R.id.week_edit);
EditText pagina_text = (EditText) findViewById(R.id.pagina_edit);
upload_task.execute(week_text, pagina_text);
}
protected class upload_task extends AsyncTask<EditText, Object, String> {
#Override
protected String doInBackground(EditText... params) {
EditText w = params[0];
EditText p = params[1];
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String ret = "Done!";
if(!bundle.isEmpty()) {
String afdeling_url = bundle.getString("afdeling_url", "DKW/");
String afdeling_preFix = bundle.getString("afdeling_preFix", "dkw");
String locatie_url = bundle.getString("locatie_url", "delf_wend");
String new_fileName = afdeling_preFix + w + p;
File f = new File(foto_path);
File sdcard = Environment.getExternalStorageDirectory();
File to = new File(sdcard, new_fileName);
f.renameTo(to);
if(f == null){
Toast.makeText(upload.this, "Geen foto geselecteerd", Toast.LENGTH_SHORT).show();
}
if(f != null) {
try{
Toast.makeText(getApplicationContext(), afdeling_url + afdeling_preFix, Toast.LENGTH_SHORT).show();
client.setPassive(true);
client.setAutoNoopTimeout(30000);
client.connect(FTP_HOST, 21);
client.login(FTP_USER, FTP_PASS);
client.setType(FTPClient.TYPE_BINARY);
client.changeDirectory(locatie_url + afdeling_url);
client.upload(to, new FTP_LISTENER());
restart();
}
catch (Exception e){
e.printStackTrace();
try {
client.disconnect(true);
Toast.makeText(getApplicationContext(), "Upload voltooid", Toast.LENGTH_SHORT);
}
catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
return ret;
}
}
My problem is as follows: i want to use the values of week_text.getText().toString(); and pagina_text.getText().toString(); in my Asynctask, but i cant find a way to achieve this.
i also have zero clue on what to do with the parameters behind Asynchtask, i have looked it up multiple times but it just doesnt make sense when using it for a FTP upload.
Help please ._.
Just pass String values to execute method like below
new upload_task().execute(edtText1.getText.toString,edtText2.getText.toString);
then
#Override
protected String doInBackground(String... params) {
String editText1Value = params[0];
String editText2Value = params[1];
///then do what ever you want
}
Just add the EditText` as parameter:
protected class upload_task extends AsyncTask<EditText, Object, String> {
#Override
protected String doInBackground(EditText... params) {
EditText editText1 = params[0];
EditText editText2 = params[1];
///rest of code:
}
}
And call it:
EditText week_text = (EditText) findViewById(R.id.week_edit);
EditText pagina_text = (EditText) findViewById(R.id.pagina_edit);
new upload_task().execute(week_text, paging_text);
Related
So I'm going to post the simple code to a program I'm writing. Here is my question. I think I'm connecting to my server just fine (Because I'm posting this online I will replace the server address with a fake one) and I want to know if I'm actually sending the variables to the server. I am sending the data to a PHP server using this string ("?systemid=demo&pwd=demo&reason=do%20something&qnumber=A36"). This is hard-coded for testing purposes. My question is, am I actually sending the data? There doesn't seem to be a send() method. Please excuse my ignorance. I'm new to Android.
My thought was that when I write to the OutputStream, I am also sending the data. Please take a look
public class PrintTicketActivity extends AppCompatActivity {
private static final String TAG2 = "PrintTicketActivity";
Context mContext;
Button mButtonA, mButtonB, mButtonC, mButtonD, mButtonE, mButtonF;
List<Button> mButtons;
List<PrintJob> mPrintJobs;
WebView mWebView;
int printJobNum = 1;
// here i'm initializing the variables with an arbitrary value so the compiler won't complain
// that they may have not been initialized in the button's onclick listeners
// these values are overwritten from sharedPreferences anyway.....the file will always exist unless there is a major problem
int numA, numB, numC, numD, numE, numF;
String buttonA, buttonB, buttonC, buttonD, buttonE, buttonF;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_print_ticket);
mContext = this;
mButtons = new ArrayList<>();
mPrintJobs = new ArrayList<>();
mButtonA = (Button) findViewById(R.id.button_a);
mButtonB = (Button) findViewById(R.id.button_b);
mButtonC = (Button) findViewById(R.id.button_c);
mButtonD = (Button) findViewById(R.id.button_d);
mButtonE = (Button) findViewById(R.id.button_e);
mButtonF = (Button) findViewById(R.id.button_f);
// add the buttons to the list so we can check later to see if any of the buttons has empty text
// and then hide the button if it is empty
mButtons.add(mButtonA);
mButtons.add(mButtonB);
mButtons.add(mButtonC);
mButtons.add(mButtonD);
mButtons.add(mButtonE);
mButtons.add(mButtonF);
// check for the start up file
File file = new File("data/data/com.myDomain.myProgram/shared_prefs/start.xml");
if (file.exists()) {
// place text from preferences on the buttons
updateUI();
} else {
Toast.makeText(mContext, "Something went wrong", Toast.LENGTH_SHORT).show();
}
mButtonA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
executeQueue(NUMBER_A, numA, "A", mButtonA);
new SendQueueToServer().execute();
}
});
mButtonB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
executeQueue(NUMBER_B, numB, "B", mButtonB);
}
});
mButtonC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
executeQueue(NUMBER_C, numC, "C", mButtonC);
}
});
mButtonD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
executeQueue(NUMBER_D, numD, "D", mButtonD);
}
});
mButtonE.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
executeQueue(NUMBER_E, numE, "E", mButtonE);
}
});
mButtonF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
executeQueue(NUMBER_F, numF, "F", mButtonF);
}
});
}
private void executeQueue(String prefKey, int num, String category, Button button) {
printTicket(button.getText().toString(), category + num);
// increment the number after printing the ticket
++num;
// update the number in the shared preferences
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS, MODE_PRIVATE).edit();
editor.putInt(prefKey, num);
editor.apply();
// update the UI to get an updated version of the queue number
updateUI();
}
private void updateUI() {
SharedPreferences preferences = getSharedPreferences(MY_PREFS, MODE_PRIVATE);
buttonA = preferences.getString(A, "");
buttonB = preferences.getString(B, "");
buttonC = preferences.getString(C, "");
buttonD = preferences.getString(D, "");
buttonE = preferences.getString(E, "");
buttonF = preferences.getString(F, "");
numA = preferences.getInt(NUMBER_A, 1);
numB = preferences.getInt(NUMBER_B, 1);
numC = preferences.getInt(NUMBER_C, 1);
numD = preferences.getInt(NUMBER_D, 1);
numE = preferences.getInt(NUMBER_E, 1);
numF = preferences.getInt(NUMBER_F, 1);
mButtonA.setText(buttonA);
mButtonB.setText(buttonB);
mButtonC.setText(buttonC);
mButtonD.setText(buttonD);
mButtonE.setText(buttonE);
mButtonF.setText(buttonF);
// if a button doesn't have anything assigned to it, hide the button
for (Button button : mButtons) {
if (button.getText().equals("")) {
button.setVisibility(View.GONE);
}
}
}
private void printTicket(String queueTitle, String queueCategory) {
// create a WebView object for printing
WebView webView = new WebView(mContext);
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
Log.i(TAG2, "page finished loading " + url);
createWebPrintJob(view);
mWebView = null;
}
});
String html = "<html><body><h2 style=\"text-align:center;font-size:60px\">" + queueTitle + "</h2><h1 style=\"text-align:center" +
";font-size:200px\">" +
queueCategory + "</h1>";
webView.loadDataWithBaseURL(null, html, "text/HTML", "UTF-8", null);
// Keep a reference to WebView object until you pass the PrintDocumentAdapter
// to the PrintManager
mWebView = webView;
}
#SuppressWarnings("deprecation")
private void createWebPrintJob(WebView webView) {
PrintManager printManager = (PrintManager) mContext.getSystemService(Context.PRINT_SERVICE);
// Get a print adapter instance
PrintDocumentAdapter printAdapter;
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
printAdapter = webView.createPrintDocumentAdapter("print_job_num" + printJobNum);
printJobNum++;
} else {
printAdapter = webView.createPrintDocumentAdapter();
printJobNum++;
}
// Create a print job with name and adapter instance
String jobName = getString(R.string.app_name) + " Document";
PrintJob printJob = printManager.print(jobName, printAdapter,
new PrintAttributes.Builder().build());
// save for status checking later
mPrintJobs.add(printJob);
}
#Override
protected void onResume() {
super.onResume();
updateUI();
}
// #Override
// public void onBackPressed() {
// // don't add superclass constructor
// // I am disabling the back button here
// }
private class SendQueueToServer extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
OutputStream out = null;
String urlParameters = "?systemid=demo&pwd=demo&reason=do%20something&qnumber=A36";
HttpsURLConnection connection = null;
try {
URL url = new URL("https://www.example.com/php");
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.connect();
out = new DataOutputStream(connection.getOutputStream());
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(out, "UTF-8"));
writer.write(urlParameters);
writer.flush();
writer.close();
Log.d(TAG2, " and the response is: " + connection.getResponseMessage());
Log.d(TAG2, "you are connected and good to go");
} catch (IOException e) {
e.printStackTrace();
} finally {
assert connection != null;
connection.disconnect();
}
return null;
}
}
}
The url parameters indicates that you are trying to make a GET request and this is not proper procedure to make an HTTP GET request. You don't need to write anything to the OutputStreamWriter if you are making a GET request. Here's a template for the same:
URL url;
HttpURLConnection urlConnection = null;
String urlParameters = "?systemid=demo&pwd=demo&reason=do%20something&qnumber=A36";
try {
url = new URL("https://www.example.com/php"+urlParameters);
urlConnection = (HttpURLConnection) url
.openConnection();
//use this block of code in case you are looking for some response from your server
InputStream in = urlConnection.getInputStream();
InputStreamReader isw = new InputStreamReader(in);
int data = isw.read();
while (data != -1) {
char current = (char) data;
data = isw.read();
System.out.print(current);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
You can use Retrofit Library to send data to Server. It's very easy to communicate with Server using this library.
Visit http://square.github.io/retrofit/ for tutorial on how to use this library in Android/Java.
I'm developing a Calorie app using an API Database. When the user clicks the search button it gets the string and then searches the database. For some reason the user edit text "string" is not being retrieved therefore not being able to search the api database. When I did the debug I noticed that the string is "" meaning empty.
Thanks again so much, New to api and android studio.
public class AddEntry extends Fragment implements View.OnClickListener {
EditText FoodET,CalorieET;
ImageButton Savebtn, Cancelbtn;
Button searchbutton;
String foodET,calorieET;
//database
private DatabaseHandler dba;
public AddEntry() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_add_entry, container,
false);
Savebtn = (ImageButton) myView.findViewById(R.id.SaveBtn);
Savebtn.setBackgroundColor(Color.TRANSPARENT);
Savebtn.setOnClickListener(this);
searchbutton = (Button) myView.findViewById(R.id.SearchButton);
searchbutton.setOnClickListener(this);
Cancelbtn = (ImageButton) myView.findViewById(R.id.CancelBtn);
Cancelbtn.setBackgroundColor(Color.TRANSPARENT);
Cancelbtn.setOnClickListener(this);
return myView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
FoodET= (EditText)view.findViewById(R.id.foodEditText);
FoodET.setInputType(InputType.TYPE_CLASS_TEXT);
CalorieET=(EditText)view.findViewById(R.id.caloriesEditText);
CalorieET.setInputType(InputType.TYPE_CLASS_NUMBER);
foodET = ((EditText)
view.findViewById(R.id.foodEditText)).getText().toString();
foodET.isEmpty();
FoodET.setText("");
CalorieET.setText("");
calorieET = ((EditText)
view.findViewById(R.id.caloriesEditText)).getText().toString();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.SearchButton:
FoodSearch search = new FoodSearch(foodET, CalorieET );
search.execute();
break;
case R.id.SaveBtn:
if (FoodET.getText().toString().equals(null) ||
CalorieET.getText().toString().equals(null)||
CalorieET.getText().toString().equals("") ||
CalorieET.getText().toString().equals("")){
Toast.makeText(getActivity(), "Please enter information",
Toast.LENGTH_LONG).show();
AlertDialog NotFound = new
AlertDialog.Builder(getContext()).create();
NotFound.setTitle("Error");
NotFound.setMessage("Food not found :(");
NotFound.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
dialog.dismiss();
}
});
}
else
((appMain) getActivity()).loadSelection(0);
break;
case R.id.CancelBtn:
// EditText descriptionET=
(EditText)getView().findViewById(R.id.foodEditText);
//descriptionET.setText("");
//EditText calorieET=
(EditText)getView().findViewById(R.id.caloriesEditText);
//calorieET.setText("");
((appMain) getActivity()).loadSelection(0);
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
private class FoodSearch extends AsyncTask<Void, Void, String> {
String food;
EditText calories;
FoodSearch(String food, EditText calories){
this.food = food;
this.calories = calories;
}
#Override
protected String doInBackground(Void... params) {
try {
food = food.replaceAll(" ", "%20");
URL url = new URL("http://api.nal.usda.gov/ndb/search/?
format=JSON&q=" + food +
"&max=1&offset=0&sort=r&api_
key=xMJV33vSmKsquFqcBwZ23oJ7DlL2abmfsrDUUx1l");
HttpURLConnection urlConnection = (HttpURLConnection)
url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
String result = stringBuilder.toString();
if(result.contains("zero results")) {
String s = "empty";
return s;
}
JSONObject object = (JSONObject) new
JSONTokener(result).nextValue();
JSONObject list = object.getJSONObject("list");
JSONArray items = list.getJSONArray("item");
String item = items.get(0).toString();
int i = item.indexOf("ndbno\":\"") + 8;
int f = item.indexOf("\"", i);
String ndbno = item.substring(i,f);
Log.d("DEBUG", ndbno);
URL url2 = new URL("http://api.nal.usda.gov/ndb/reports/?
ndbno=" + ndbno +
"&type=b&format=JSON&api_
key=xMJV33vSmKsquFqcBwZ23oJ7DlL2abmfsrDUUx1l");
HttpURLConnection urlConnection2 = (HttpURLConnection)
url2.openConnection();
BufferedReader bufferedReader2 = new BufferedReader(new
InputStreamReader(urlConnection2.getInputStream()));
StringBuilder stringBuilder2 = new StringBuilder();
String line2;
while ((line2 = bufferedReader2.readLine()) != null) {
stringBuilder2.append(line2).append("\n");
}
bufferedReader2.close();
String res = stringBuilder2.toString();
int index = res.indexOf("\"unit\": \"kcal\",") + 46;
int index2 = res.indexOf("\"", index);
String calories = res.substring(index,index2);
urlConnection2.disconnect();
return calories;
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
String s = "empty";
return s;
}
}
protected void onPostExecute(String response) {
if(!response.isEmpty() && !response.equals("empty")) {
calories.setText(response);
} else {
AlertDialog foodNotFound = new
AlertDialog.Builder(getContext()).create();
foodNotFound.setTitle("Error");
foodNotFound.setMessage("Food not found :(");
foodNotFound.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
dialog.dismiss();
}
});
}
}
}
}
Try this
case R.id.SearchButton:
String foodEtString=FoodET.getText().toString();
FoodSearch search = new FoodSearch(foodEtString, CalorieET );
search.execute();
break;
And Add this in onCreate as well
FoodET= (EditText)view.findViewById(R.id.foodEditText);
FoodET.setInputType(InputType.TYPE_CLASS_TEXT);
CalorieET=(EditText)view.findViewById(R.id.caloriesEditText);
CalorieET.setInputType(InputType.TYPE_CLASS_NUMBER);
Use these values instead when you go to execute the AsyncTask
String FoodName = FoodET.getText().toString().trim();
String calString = CalorieET.getText().toString().trim();
The following values are always empty when the view is created (and are not necessary in your code).
foodET = ((EditText) view.findViewById(R.id.foodEditText)).getText().toString();
calorieET = ((EditText) view.findViewById(R.id.caloriesEditText)).getText().toString();
So that explains why this didn't work
FoodSearch search = new FoodSearch(foodET, CalorieET );
You should always try to call getText in response to a user event in order to get the most recent value(s) of the input fields
I'd also suggest that you learn how to properly parse JSON data (don't use indexOf), or go so far as look into the Retrofit library
I am browsing an xml file from external usb storage (using otg cable, connected in the tablet/android phone) to be parsed.
Steps:
Browse for the file from external usb storage
Parse the xml file
Save the file in a text file
For the time being, I am now able to browse and parse the xml file then display the parsed file wherein it shows the needed information in a listview. Now, I want to save the displayed information as a text file and save it to the external sd card of the tablet. Here's the code:
Model.java :
public class Model {
String _model;
String _part;
String _sw;
String _desc;
// constructor
public Model() {
}
// constructor with parameters
public Model(String model, String part, String sw, String desc) {
this._model = model;
this._part = part;
this._sw = sw;
this._desc = desc;
}
// Set all methods
public void setModel(String model) {
this._model = model;
}
public void setPart(String part) {
this._part = part;
}
public void setSw(String sw) {
this._sw = sw;
}
public void setDesc(String desc) {
this._desc = desc;
}
// Get all methods
public String getModel() {
return this._model;
}
public String getPart() {
return this._part;
}
public String getSw() {
return this._sw;
}
public String getDesc() {
return this._desc;
}
//
#Override
public String toString() {
return "\n" + "Device" + "\n" + "\n"
+ "Model ID : " + _model + "\n"
+ "Part Number : " + _part + "\n"
+ "Software Version: " + _sw + "\n"
+ "Description : " + _desc ;
}
}
ModelParser.java :
public class ModelParser extends DefaultHandler{
static final String ERROR = "Errors";
static final String ID = "ID";
static final String PART = "PartNumber";
static final String SW = "SoftwareVersion";
static final String DESC = "Description";
private boolean done = false;
private String currentTag = null;
private Model current = null;
private ArrayList<Model> model = new ArrayList<Model>();
public ArrayList<Model> getItemsList() {
return model;
}
public ArrayList<Model> parse(Context context) {
try {
String file = ReadSystemActivity.getFilename();
file.toString();
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
FileInputStream fis = new FileInputStream(file);
parser.setInput(new InputStreamReader(fis));
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT && !done) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
model = new ArrayList<Model>();
break;
case XmlPullParser.START_TAG:
currentTag = parser.getName();
if (currentTag.equalsIgnoreCase(ERROR)) {
current = new Model();
}
else if (current != null) {
if (currentTag.equalsIgnoreCase(ID)) {
current.setModel(parser.nextText());
} else if (currentTag.equalsIgnoreCase(PART)) {
current.setPart(parser.nextText());
} else if (currentTag.equalsIgnoreCase(SW)) {
current.setSw(parser.nextText());
}else if (currentTag.equalsIgnoreCase(DESC)) {
current.setDesc(parser.nextText());
}
}
break;
case XmlPullParser.END_TAG:
currentTag = parser.getName();
if (currentTag.equalsIgnoreCase(ERROR) && current != null) {
model.add(current);
} else if (currentTag.equalsIgnoreCase(ERROR)) {
done = true;
}
break;
}
eventType = parser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return model;
}
}
And ReadActivity.java :
public class ReadActivity extends ListActivity implements OnClickListener {
public List<Model> model = null;
private String filename = "SystemInfo.txt";
String modd = modId.getModel();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read);
new LoadSystemTask().execute();
Button save = (Button) findViewById(R.id.btnSave);
save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
if (isSDCardWritable()) {
StringBuilder locationStrBuilder = new StringBuilder();
locationStrBuilder.append("Model ID: "+ modd);
String locationStr = locationStrBuilder.toString();
try {
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath()+"/FileReader");
directory.mkdirs();
File myFile = new File(directory, filename);
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile, true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(locationStr);
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Done writing to SD Card",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
} }
else
{
// SD Card Not Available
Toast.makeText(getBaseContext(),"SD Card Not Available",Toast.LENGTH_SHORT).show();
} //else
}// onClick
}); // btnSave
}
private class LoadSystemTask extends AsyncTask<String, Void, List<Model>> {
#Override
protected List<Model> doInBackground(String... args) {
// CALL XMLPULLPARSER & RETURN A LIST
ModelParser parser = new ModelParser();
model = parser.parse(getBaseContext());
return model;
}
#Override
protected void onPostExecute(List<Model> models) {
ArrayAdapter<Model> adapter = new ArrayAdapter<Model>(getBaseContext(), android.R.layout.simple_list_item_1, models);
setListAdapter(adapter);
}
}
public boolean isSDCardWritable() {
String status = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(status))
{
return true;
}
return false;
} //isSDCardWritable
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Problem is, I want to save the Id but I am getting a null value in the SystemInfo.txt when I click the save button.
You're storing model inside another object and trying to retrieve it from a new object.
This is where you're storing your model object inside ModelParser
current = new GarminModel()
whereas you're trying to retrieve it from a new object inside ReadActivity
GarminModel modId = new GarminModel();
String modd = modId.getModel();
Get reference to your Model arraylist by calling ModelParser's getItemsList() inside ReadActivity and from it try to get your model objects
Check position of below two lines in the code below
ModelParser parser = new ModelParser();
ArrayList<Model> modelList = parser.getItemsList();
Model modd = modelList.get(0);
Note that you need to remove ModelParser parser = new ModelParser(); from LoadSystemTask
public class ReadActivity extends ListActivity implements OnClickListener {
public List<Model> model = null;
private String filename = "SystemInfo.txt";
ModelParser parser = new ModelParser();
//-----------------
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read);
new LoadSystemTask().execute();
Button save = (Button) findViewById(R.id.btnSave);
save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
if (isSDCardWritable()) {
ArrayList<Model> modelList = parser.getItemsList();
//-----
Model modd = modelList.get(0);
StringBuilder locationStrBuilder = new StringBuilder();
locationStrBuilder.append("Model ID: "+ modd);
String locationStr = locationStrBuilder.toString();
try {
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File(sdCard.getAbsolutePath()+"/FileReader");
directory.mkdirs();
File myFile = new File(directory, filename);
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile, true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(locationStr);
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),"Done writing to SD Card",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),Toast.LENGTH_SHORT).show();
} }
else
{
// SD Card Not Available
Toast.makeText(getBaseContext(),"SD Card Not Available",Toast.LENGTH_SHORT).show();
} //else
}// onClick
}); // btnSave
}
private class LoadSystemTask extends AsyncTask<String, Void, List<Model>> {
#Override
protected List<Model> doInBackground(String... args) {
// CALL XMLPULLPARSER & RETURN A LIST
model = parser.parse(getBaseContext());
return model;
}
I have two activities:
1.Main Activity which contains listview;
2.Second Activity which add item to listview in Main Activity.
For Second Activity I created layout-land layout for landscape.
After Second Activity is opens in portrait, I change it to landscape mode - Second Activity close and app return to Main Activity.
Questions:
1.How save entered to EditText fields values after orientation is changed?
2.And how to apply layout-land to Second Activity when change screen orientation to landscape?
UPD
Second activity code:
public class AddItem extends MainScreen implements OnClickListener{
final String LOG_TAG = "myLogs";
EditText comment_enter, link_enter, password_enter, login_enter, title_enter, date_enter;
Button add_item_button, add_more_button, clear_close_button;
CheckBox showPass;
DBHelper db;
DataBase DB;
SimpleCursorAdapter passListViewAdapter;
SimpleDateFormat sdf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_item);
Log.d(LOG_TAG, "before edit : ");
comment_enter = (EditText) findViewById(R.id.comment_enter);
link_enter = (EditText) findViewById(R.id.link_enter);
password_enter = (EditText) findViewById(R.id.password_enter);
login_enter = (EditText) findViewById(R.id.login_enter);
title_enter = (EditText) findViewById(R.id.title_enter);
date_enter = (EditText) findViewById(R.id.date_enter);
showPass = (CheckBox) findViewById(R.id.showPass);
showPass.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Log.d(LOG_TAG, "is checked : " + isChecked);
if (isChecked) {
password_enter.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
}
else {
password_enter.setInputType(129);
}
}
});
add_item_button = (Button) findViewById(R.id.add_item_button);
add_item_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d(LOG_TAG, "add_item_button : ");
String title_str = title_enter.getText().toString();
String login_str = login_enter.getText().toString();
String pass_str = password_enter.getText().toString();
String link_str = link_enter.getText().toString();
String comm_str = comment_enter.getText().toString();
String date_str = date_enter.getText().toString();
byte[] login_byted = null;
try {
login_byted = login_str.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String login_crypted = Base64.encodeToString(login_byted, Base64.DEFAULT);
Log.d(LOG_TAG, "Crypted login" + login_crypted);
byte[] pass_byted = null;
try {
pass_byted = pass_str.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String pass_crypted = Base64.encodeToString(pass_byted, Base64.DEFAULT);
Log.d(LOG_TAG, "Crypted login" + pass_crypted);
DataBase DB = new DataBase(AddItem.this);
DB.open();
DB.insertPass(title_str, login_crypted, pass_crypted, link_str, comm_str, date_str);
DB.close();
Log.d(LOG_TAG, "after inserting into DB : ");
finish();
}
});
add_more_button = (Button) findViewById(R.id.add_more_button);
add_more_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d(LOG_TAG, "add_more_button : ");
String title_str = title_enter.getText().toString();
String login_str = login_enter.getText().toString();
String pass_str = password_enter.getText().toString();
String link_str = link_enter.getText().toString();
String comm_str = comment_enter.getText().toString();
String date_str = date_enter.getText().toString();
byte[] login_byted = null;
try {
login_byted = login_str.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String login_crypted = Base64.encodeToString(login_byted, Base64.DEFAULT);
Log.d(LOG_TAG, "Crypted login" + login_crypted);
byte[] pass_byted = null;
try {
pass_byted = pass_str.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String pass_crypted = Base64.encodeToString(pass_byted, Base64.DEFAULT);
Log.d(LOG_TAG, "Crypted login" + pass_crypted);
DataBase DB = new DataBase(AddItem.this);
DB.open();
DB.insertPass(title_str, login_crypted, pass_crypted, link_str, comm_str, date_str);
DB.close();
Log.d(LOG_TAG, "after inserting into DB : ");
fieldClear();
String link_enter_str = link_enter.getText().toString();
if(link_enter_str.equals("")){
link_enter.setText("http://www.");
}
}
});
clear_close_button = (Button) findViewById(R.id.clear_close_button);
clear_close_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d(LOG_TAG, "clear/close click button : ");
boolean checkRes = emptyAllCheck();
Log.d(LOG_TAG, "result : " + checkRes);
if(checkRes == true){
finish();
}
fieldClear();
}
});
if(savedInstanceState != null){
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
Log.d(LOG_TAG, "title : " + savedInstanceState.getString("title"));
title_enter.setText(savedInstanceState.getString("title"));
login_enter.setText(savedInstanceState.getString("login"));
password_enter.setText(savedInstanceState.getString("pass"));
link_enter.setText(savedInstanceState.getString("link"));
comment_enter.setText(savedInstanceState.getString("comm"));
date_enter.setText(savedInstanceState.getString("date"));
add_item_button = (Button) findViewById(R.id.add_item_button);
add_more_button = (Button) findViewById(R.id.add_more_button);
}
else {
Log.d(LOG_TAG, "before getting date : ");
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
String date = sdf.format(new Date(System.currentTimeMillis()));
date_enter.setText(date);
}
}
#Override
protected void onPause() {
super.onPause();
finish();
Log.d(LOG_TAG, "onPause : ");
}
#Override
protected void onResume(){
super.onResume();
}
protected void onSaveInstanceState(Bundle saveInstance) {
super.onSaveInstanceState(saveInstance);
String title_str = title_enter.getText().toString();
String login_str = login_enter.getText().toString();
String pass_str = password_enter.getText().toString();
String link_str = link_enter.getText().toString();
String comm_str = comment_enter.getText().toString();
String date_str = date_enter.getText().toString();
saveInstance.putString("title", title_str);
saveInstance.putString("login", login_str);
saveInstance.putString("pass", pass_str);
saveInstance.putString("link", link_str);
saveInstance.putString("comm", comm_str);
saveInstance.putString("date", date_str);
Log.d(LOG_TAG, "onSaveInstanceState +" + title_str + login_str + pass_str + link_str + comm_str + date_str);
}
public void fieldClear(){
comment_enter.setText("");
link_enter.setText("http://www.");
password_enter.setText("");
login_enter.setText("");
title_enter.setText("");
}
public boolean emptyAllCheck(){
String title_str = title_enter.getText().toString();
String login_str = login_enter.getText().toString();
String pass_str = password_enter.getText().toString();
String link_str = link_enter.getText().toString();
String comm_str = comment_enter.getText().toString();
if (title_str.equals("") && login_str.equals("") && pass_str.equals("") && link_str.equals("http://www.") && comm_str.equals("")) {
return true;
}
return false;
}
}
i advise you to read a bit more about Android Activity life cycle it will help you.
However on configuration Change android destroy you are activity and recreate and you can use the callback method OnsavedInstanceState() to save you instance (it will be call automatically by the system on configuration change)
example
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);{
String savedText = myEditText.getText().toString();
savedInstanceState.putString("Key", savedText);
}
Now when the app is recreated on OnCreate method retrieve your saved text as follow :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState != null){
myEditText.setText(savedInstanceState.getString("Key");
//the rest of the code}
Voila and I hope that is that you meant.
use this one:
android:configChanges="orientation|screenSize"
add this code in your manifest file. No need to save the edit text variable.
I have an app that in one of it's Activities uses AsyncTask to call a method from another class that hooks up to a database to varify a user's login credentials. The Activity EntryActivity Has three member variable that need to be updated with the result of the AsyncTask, carerID, firstName and surName . When I first run the App all three variables are null but if i press the login button a second time the variables are set correctly and the app behaves as it should.
Is there a reason why the three member variables are not set correctly from onPostxecute in the first run of the app?
.
public class EntryActivity extends NfcBaseActivity{
private LoginWebservice loginWebservice;
private static final String TAG = EntryActivity.class.getSimpleName();
private Button login;
private EditText userName;
private EditText passwordPin;
NfcScannerApplication nfcscannerapplication;
public static final String CUSTOM_QRCODE_ACTION = "com.carefreegroup.QRCODE_ACTION";
private String carerID;
private String firstName;
private String surName;
private boolean isValidated = false;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.entryscreen);
nfcscannerapplication = (NfcScannerApplication) getApplication();
loginWebservice = new LoginWebservice(this);
carerID = null;
firstName = null;
surName = null;
userName = (EditText)findViewById(R.id.username);
passwordPin = (EditText)findViewById(R.id.password);
login = (Button)findViewById(R.id.buttonlogin);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
////////////get user's input///////////
String compId = "100";
String theUsername = userName.getText().toString();
String thePassword = passwordPin.getText().toString();
String loginType = "1";
String[] params = new String[]{compId, theUsername, thePassword, loginType};
//validate user Asynchonously on background thread
new AsyncValidateCarer().execute(params);
Log.e(TAG, "carerid =" + carerID + " firstname = " + firstName + " surnamee = " + surName);
DateTime now = new DateTime();
long loginTime = now.getMillis();
String fullName = firstName +" " + surName;
Log.e(TAG, "fullname = " + fullName);
if(carerID != null){
ContentValues loginValues = new ContentValues();
loginValues.putNull(LoginValidate.C_ID_INDEX);
loginValues.put(LoginValidate.C_CARER_ID, carerID);
loginValues.put(LoginValidate.C_COMP_ID, compId);
loginValues.put(LoginValidate.C_CARER_NAME, fullName);
loginValues.put(LoginValidate.C_PASSWORD, thePassword);
loginValues.put(LoginValidate.C_DATE_TIME, loginTime);
nfcscannerapplication.loginValidate.insertIntoCarer(loginValues);
Toast.makeText(
EntryActivity.this,
"Carer logged in to System",
Toast.LENGTH_LONG).show();
isValidated = true;
Intent intent = new Intent(EntryActivity.this,
NfcscannerActivity.class);
intent.setAction(CUSTOM_QRCODE_ACTION);
startActivity(intent);
}else{
Toast.makeText(
EntryActivity.this,
"Please check credentials",
Toast.LENGTH_LONG).show();
}
//////////////validate user/////////////////
}
});
Button changeUser = (Button)findViewById(R.id.buttonchangeuser);
changeUser.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.e(TAG, "change user button clicked");
nfcscannerapplication.loginValidate.deleteTableCarer();
Toast.makeText(
EntryActivity.this,
"Carer logged out",
Toast.LENGTH_LONG).show();
EntryActivity.this.onCreate(savedInstanceState);
}
});
}//end of onCreate
private void hideSoftKeyboard() {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(passwordPin.getWindowToken(), 0);
}
private class AsyncValidateCarer extends AsyncTask<String, Void, ContentValues> {
#Override
protected ContentValues doInBackground(String... params) {
ContentValues cv = null;
try {
Log.e(TAG, "inside asynctask");
cv = loginWebservice.validateCarer(params[0], params[1], params[2], params[3]);
if (cv != null){
Log.e(TAG, "cv = not null!");
}
} catch (Exception e) {
e.printStackTrace();
}
return cv;
}
#Override
protected void onPostExecute(ContentValues result) {
Log.e(TAG, "inside onpostexecute");
EntryActivity.this.carerID = (String) result.get("carerID");
EntryActivity.this.firstName = (String) result.get("firstname");
EntryActivity.this.surName = (String) result.get("surname");
}
}
}
[update]
private class AsyncValidateCarer extends AsyncTask<String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
ContentValues cv = null;
try {
Log.e(TAG, "inside doInBackground");
cv = loginWebservice.validateCarer(params[0], params[1], params[2], params[3]);
carerID = (String) cv.get("carerID");
firstName = (String) cv.get("firstname");
surName = (String) cv.get("surname");
if (cv != null){
Log.e(TAG, "cv = not null! and exiting doInBackground");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
An AsyncTask will execute asynchronously so you have no guarantee that after the "execute" method call, the task is actually finished. My advice would be to move everything (or at least what is related to those fields) that are after "execute" call in "onPostExecute" method.
The reason why it seems the first click doesn't work and the second works, is that between the first "Login" click and the second one, you wait enough for the AsyncTask to finish. So when you click for the second time you see the results of the first execution. Please add some "Log" messeges in "onPostExecute" to understand what is going on.
Hope it helps:)
carerID = null;
firstName = null;
surName = null;
Remove the above there statements from the onCreate() method, as they have been initialized to their default values as they are in the Class Scope and are known as Instance Variables.