Saving Data from multiple inputs to file - java

I am developing an android application where the user has to enter text into multiple 'edittext' boxes and then i am trying to take the entered data and save it to a text file. I have got my application to save the data from the first few boxes. I have tried many approaches such as using a for loop and others but it still doesn't work. I'm currently using an array list by adding the first few bits of data to the list, writing it to the text file, clearing the list then adding the rest of the data and trying to append that to the file.
In debugging the application gets as far as adding the first bit of the new data and stops, without crashing or any errors.
This is my code:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
private Button submitForm,resetForm,btnEmail;
private String saveName;
private EditText name,depot,date,time,location,details,outcome,did;
private String attachedPathFile;
private File folder;
File myFile;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//StrictMode.enableDefaults();
name = (EditText)findViewById(R.id.nameText);
depot = (EditText)findViewById(R.id.DepotText);
date = (EditText)findViewById(R.id.DateText);
time = (EditText)findViewById(R.id.LocationText);
details = (EditText)findViewById(R.id.IncidentText);
outcome = (EditText)findViewById(R.id.OutcomeText);
did = (EditText)findViewById(R.id.DetailsText);
submitForm = (Button)findViewById(R.id.SubmitButton);
submitForm.setOnClickListener(new OnClickListener(){
#SuppressLint("SimpleDateFormat")
public void onClick(View v) {
// write on SD card file data in the text box
try {
folder = new File(Environment.getExternalStorageDirectory(),"Close Call Reports");
folder.mkdirs();
saveName = new SimpleDateFormat("yyyy-MM-dd HH mm ss").format(new Date());
myFile = new File(Environment.getExternalStorageDirectory().toString()+"/Close Call Reports/"+saveName+".txt");
myFile.createNewFile();
// FileOutputStream fOut = new FileOutputStream(myFile, true);
// OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
//
// //gets text data to write to file
// String data = "Your Name: "+name.getText().toString()+"\n"+"Your Depot: "+depot.getText().toString()+"\n"+"Date: "+
// date.getText().toString()+"\n"+"Time: "+time.getText().toString()+"\n";
// String data2 ="Location: "+location.getText().toString()+
// "\n"+ "Incident: "+details.getText().toString()+"\n"+"Potential Outcome: "+outcome.getText().toString()+"\n"+
// "What did you do ? "+did.getText().toString();
List<String> data = new ArrayList<String>();
data.add("Your Name: "+name.getText().toString());
data.add("Your Depot: "+depot.getText().toString());
data.add("Date: "+date.getText().toString());
data.add("Time: "+time.getText().toString());
appendToFile(data);
data.clear();
Log.v("DEBUGGING", "got here 1");
//data = new ArrayList<String>();
data.add("Location: "+location.getText().toString());
data.add("Incident: "+details.getText().toString());
data.add("Potential Outcome: "+outcome.getText().toString());
data.add("What did you do ? "+did.getText().toString());
Log.v("DEBUGGING", "got here 2");
appendToFile(data);
Log.v("DEBUGGING", "got here 3");
// myOutWriter.append(data);
// myOutWriter.close();
// fOut.close();
// Toast.makeText(getBaseContext(),
// "Done writing Comment File",
// Toast.LENGTH_SHORT).show();
name.setText("");
depot.setText("");
date.setText("");
time.setText("");
location.setText("");
details.setText("");
outcome.setText("");
did.setText("");
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
// write on SD card file data in the text box
}// onClick
}); // btnWriteSDFile
btnEmail = (Button)findViewById(R.id.Emailbtn);
btnEmail.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
String[] emailTo = new String[]{"ameyandroidapp#gmail.com"};
String subject = "Close Call Reporting";
String [] filePaths= new String[1];
//if(filePaths[0]==null){
for(int a=0; a < filePaths.length;a++){
attachedPathFile = Environment.getExternalStorageDirectory().toString()+"/Close Call Reports/"+saveName+".csv";
//path+ls+saveName+"("+a+")"+".txt";
filePaths[a] = attachedPathFile;
}
sendEmail(emailTo,subject,filePaths);
// }else{
// Toast.makeText(getBaseContext(),"No Files To Email",Toast.LENGTH_LONG).show();
//}
}
});
resetForm = (Button)findViewById(R.id.ResetButton);
resetForm.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
name.setText("");
depot.setText("");
date.setText("");
time.setText("");
location.setText("");
details.setText("");
outcome.setText("");
did.setText("");
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void sendEmail(String[] emailTo, String subject,
String[] filePaths) {
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
emailIntent.setData(Uri.parse("mailto: "));
emailIntent.putExtra(Intent.EXTRA_EMAIL, emailTo);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.setType("message/rfc822");
ArrayList<Uri> uris = new ArrayList<Uri>();
for(String file: filePaths){
File fileIn = new File(file);
Uri u = Uri.fromFile(fileIn);
uris.add(u);
}
//emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM,uris);
emailIntent.putExtra(android.content.Intent.EXTRA_STREAM, uris);
startActivity(Intent.createChooser(emailIntent, "Email"));
}
#Override
public void onClick(View v) {
}
public void appendToFile (List<String> SarrayList) {
BufferedWriter bw = null;
boolean myappend = true;
try {
bw = new BufferedWriter(new FileWriter(myFile, myappend));
for(String line: SarrayList ) {
bw.write(line);
bw.newLine();
}
bw.flush();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (bw != null) try {
bw.close();
} catch (IOException ioe2) {
// ignore it or write notice
}
}
}
}

I'm surprised you're not seeing it crash, as it looks to me like you should be getting a NullPointerException as you don't seem to be setting the value of location. Also, it looks wrong that you're setting the value of time using the view with ID R.id.LocationText:
time = (EditText)findViewById(R.id.LocationText);
but it's difficult to be sure without knowing what you're doing exactly.

Related

An error occurred while trying to read the text from the file

Developing a program that reads text from a file and shows it in a dynamic layout.
However, if you execute the code below, the error as below appears.
Can I get a solution?
The code is as below.
ReadFile is a function that reads text from files in file paths received by a factor, and MakeLinearLayout shows some of the text it has read through a TextView in a dynamic layout.
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.applandeo.Tempus.R;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
#SuppressLint("SdCardPath")
public class FriendListActivity extends AppCompatActivity {
final static String FilePath= "/data/data/com.applandeo.materialcalendarsampleapp/files/friendList.txt";
LinearLayout lm;
public FriendListActivity(LinearLayout lm) {
this.lm = lm;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_friend_list);
Button addButton = findViewById(R.id.addButton);
addButton.setOnClickListener(v -> {
Intent intent = new Intent(this, AddFriendsActivity.class);
startActivity(intent);
});
lm = findViewById(R.id.ll);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.WRAP_CONTENT);
MakeLinearLayout(lm);
}
public String ReadFile (String path){
StringBuffer strBuffer = new StringBuffer();
try {
InputStream is = new FileInputStream(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = "";
while ((line = reader.readLine()) != null) {
strBuffer.append(line+"\n");
}
reader.close();
is.close();
}
catch(Exception e){
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String exceptionAsStrting = sw.toString();
Log.e("Fileread", exceptionAsStrting);
e.printStackTrace();
Toast.makeText(this.getApplicationContext(), "Failed to read file.", Toast.LENGTH_SHORT).show();
return "";
}
return strBuffer.toString();
}
public void MakeLinearLayout (LinearLayout lm){
String read = ReadFile(FilePath);
String[] readArr = read.split("\\-");
if (readArr != null)
{
int nCnt = readArr.length;
// readArr[0+5n]: phone number, readArr[1+5n]: registration name, readArr [2+5n]: email, readArr[3+5n]: group name, readArr[4+5n]: note
for (int i=0; i<nCnt; ++i)
{
Log.i("ARRTAG", "arr[" + i + "] = " + readArr[i]);
}
for(int n=0; ;n++){
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
TextView InfoView = new TextView(this);
InfoView.setText(" " + read);
//InfoView.setText(" " + readArr[5*n+1] + " " + readArr[5*n+3]);
ll.addView(InfoView);
lm.addView(ll);
}
}
else{
Toast.makeText(this.getApplicationContext(), "No acquaintances have been added.", Toast.LENGTH_SHORT).show();
}
}
}
The second error occurred after reflecting the contents of the comment.
Remove below constructor from your activity code. There is no way you can pass parameters to constructor of your activity
public FriendListActivity(LinearLayout lm) {
this.lm = lm;
}

How to stop a file from overwriting itself when using FileOutputStream using openFileOutput in Android

I'm currently making an app that needs to save the number and write it into a text file. But every time it writes to the file. It overwrites the last things saved. Here is the code of the entire program in java.
package com.galaxy.nestetrisscores;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import java.io.FileOutputStream;
import java.io.File;
import android.view.View;
import android.widget.*;
public class MainActivity extends AppCompatActivity {
private Button button;
private EditText editNumber;
private String file = "Scores.txt";
private String fileContents;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
editNumber = findViewById(R.id.editNumber);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fileContents = editNumber.getText().toString();
try {
FileOutputStream fOut = openFileOutput(file, MODE_PRIVATE);
fOut.write(fileContents.getBytes());
fOut.close();
File fileDir = new File(getFilesDir(), file);
Toast.makeText(getBaseContext(), "File Saved at" + fileDir, Toast.LENGTH_LONG).show();
} catch(Exception e) {
e.printStackTrace();
}
}
});
}
}
Use the append mode when constructing the FileOutputStream.
FileOutputStream fOut = openFileOutput(file, MODE_PRIVATE | MODE_APPEND);
Not sure if this will be of any use, but a simple IF using the .exists() boolean method
File file = new File("file.txt");
if (file.exists()) {
System.err.println("File already exists");
// Append to file
} else {
// Create File
}

Saving string array list to internal file directory android

I'm currently developing an android application with makes some user data while running which is saved in two ArrayList. Once the application closes, I need to save the datas on to the internal memory but in my logcat I'm always getting the error IOException file not found.
I'm confused about why it always happen. The following is my code for my activity. Please help me!
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.text.Html;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
public static ArrayList<String> myArrayList=new ArrayList<String>();
public static ArrayList<String> myArrayListwr=new ArrayList<String>();
static int close=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
close=1;
System.out.println("Oncreate called");
try{
final File dir = new File(getApplicationContext().getFilesDir() + "/file");
if(!(dir.exists()))
{
dir.mkdirs(); //create folders where write files
}
final File file = new File(dir+ "/lines.txt");
if(!(file.exists())) {
file.createNewFile();
}
BufferedReader br = new BufferedReader(new FileReader(file));
if (br.readLine() == null) {
close=0;
}
br.close();
}
catch (IOException exc) { exc.printStackTrace(); }
try {
if(myArrayList.size()==0 && close!=0)
{
System.out.println("retriving data from file lines");
FileInputStream input =openFileInput("lines.txt"); // Open input stream
DataInputStream din = new DataInputStream(input);
int sz = din.readInt(); // Read line count
for (int i=0;i<sz;i++) { // Read lines
String line = din.readUTF();
myArrayList.add(line);
}
din.close();
}
}
catch (IOException exc) { exc.printStackTrace(); }
try {
if(myArrayListwr.size()==0 && close!=0)
{
System.out.println("retriving data from file lineswr");
final File dirwr = new File(getApplicationContext().getFilesDir() + "/file");
if(!dirwr.exists())
dirwr.mkdirs(); //create folders where write files
final File filewr = new File(dirwr+ "/lineswr.txt");
if(!filewr.exists()) {
filewr.createNewFile();
}
FileInputStream inputwr = openFileInput("lineswr.txt"); // Open input stream
DataInputStream dinwr = new DataInputStream(inputwr);
int szwr = dinwr.readInt(); // Read line count
for (int iwr=0;iwr<szwr;iwr++) { // Read lines
String linewr = dinwr.readUTF();
myArrayListwr.add(linewr);
}
dinwr.close();
}
}
catch (IOException exc) { exc.printStackTrace(); }
Button phy = (Button) findViewById(R.id.button3);
Button mat = (Button) findViewById(R.id.button1);
Button bio = (Button) findViewById(R.id.button2);
Button chem = (Button) findViewById(R.id.button4);
}
#Override
public void onBackPressed() {
super.onBackPressed();
try {
if(myArrayList.size()!=0)
{
System.out.println("inside on back pressed saving data to lines");
//Modes: MODE_PRIVATE, MODE_WORLD_READABLE, MODE_WORLD_WRITABLE
String fileName = getApplicationContext().getFilesDir()+"/file/"+ "lines.txt";
FileOutputStream output = openFileOutput("lines.txt",MODE_PRIVATE);
DataOutputStream dout = new DataOutputStream(output);
dout.writeInt(myArrayList.size()); // Save line count
for(String line : myArrayList) // Save lines
dout.writeUTF(line);
dout.flush(); // Flush stream ...
dout.close(); // ... and close.
}
}
catch (IOException exc) { exc.printStackTrace(); }
try {
if(myArrayListwr.size()!=0)
{
System.out.println("inside on back pressed saving data to lineswr");
//Modes: MODE_PRIVATE, MODE_WORLD_READABLE, MODE_WORLD_WRITABLE
String fileNamewr = getApplicationContext().getFilesDir()+"/file/"+ "lineswr.txt";
FileOutputStream outputwr = openFileOutput("lineswr.txt",MODE_PRIVATE);
DataOutputStream doutwr = new DataOutputStream(outputwr);
doutwr.writeInt(myArrayListwr.size()); // Save line count
for(String linewr : myArrayListwr) // Save lines
doutwr.writeUTF(linewr);
doutwr.flush(); // Flush stream ...
doutwr.close(); // ... and close.
}
}
catch (IOException exc) { exc.printStackTrace(); }
Intent intent = new Intent(MainActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
}
}

AssetManager null pointer exception

I'm getting a null pointer exception on the line marked with /Here/ in my code. I've spent about 2 hours looking up the AssetManager and how to use it, etc, but still can't figure out why it's null. I've called getAssets() by itself, from the context and from the resources but still I'm getting null. Can anyone help me out here?
Thanks.
package com.hamc17.CatFacts;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
public class FactsActivity extends Activity{
Context context;
Resources res;
#Override
public void onCreate(Bundle savedInstanceBundle){
super.onCreate(savedInstanceBundle);
context = getApplicationContext();
res = context.getResources();
Button getFactButton = (Button) findViewById(R.id.getFactButton);
getFactButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast toastMessageOnClick = new Toast(FactsActivity.this);
toastMessageOnClick.setText(getFact());
if((toastMessageOnClick.toString()).length()>50)
{
toastMessageOnClick.setDuration(10);
}
else
{
toastMessageOnClick.setDuration(Toast.LENGTH_LONG);
}
toastMessageOnClick.show();
}
});
}
String[] factArray = getFactsFromTextFile().split(";");
private String getFactsFromTextFile(){
/*Here*/ AssetManager assMan = context.getAssets();
try{
BufferedReader buff = new BufferedReader(new InputStreamReader(assMan.open("facts.txt")));
String line;
StringBuilder build = new StringBuilder();
while((line = buff.readLine()) != null)
{
build.append(line).append(System.getProperty("line.seperator"));
}
return build.toString();
}
catch (IOException e)
{
Toast toastMessage = new Toast(getApplicationContext());
toastMessage.setText(e.toString() + "\n Whoops, there was an error! ");
toastMessage.show();
return "";
}
finally
{
try{
assMan.close();
}
catch (Exception e)
{
//Whatever Trevor
}
}
}
private String getFact(){
String randomFactString = "";
int factCount = factArray.length;
Random rng = new Random();
int randomNum = rng.nextInt()*factCount;
randomFactString = factArray[randomNum];
return randomFactString;
}
}
You are missing setContentView(R.layout.mylayout);
#Override
public void onCreate(Bundle savedInstanceBundle){
super.onCreate(savedInstanceBundle);
setContentView(R.layout.mylayout);
Button getFactButton = (Button) findViewById(R.id.getFactButton);
findViewById looks for a resource with the id in the current inflated layout. So you should set the content of your layout to the activity before initializing views
Also you can use
res = getResources();
Instead of creating a local variable to get the Context of the Activity just use getBaseContext(); each time you want to get the reference to the Context.
So something like this instead:
AssetManager assMan = getBaseContext().getAssets();

POST not occuring on Android?

Hey so I am not getting an error, but all my logs get initiated except for the one after HttpResponse not sure why, and on the server end I do not see any activity of a POST coming in...
here is my code:
package com.sfsfdsfds;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class wardrobe extends Activity{
//set variable for the fields
private EditText nameField;
private Spinner typeField;
private EditText colorField;
private Spinner seasonField;
private EditText sizeField;
private EditText quantityField;
private ImageView imageField;
private ProgressBar progressBarField;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wardrobe);
ImageView user_photo = (ImageView) findViewById(R.id.user_photo);
//button for upload image
Button uploadImageButton = (Button) findViewById(R.id.uploadImageButton);
//button for posting details
Button postWardrobe = (Button) findViewById(R.id.postButton);
//Value of fields
nameField = (EditText) findViewById(R.id.nameFieldWardrobeScreen);
typeField = (Spinner) findViewById(R.id.typeFieldWardrobeScreen);
colorField = (EditText) findViewById(R.id.colorFieldWardrobeScreen);
seasonField = (Spinner) findViewById(R.id.seasonFieldWardrobeScreen);
sizeField = (EditText) findViewById(R.id.sizeFieldWardrobeScreen);
quantityField = (EditText) findViewById(R.id.quantityFieldWardrobeScreen);
imageField = (ImageView) findViewById(R.id.user_photo);
progressBarField = (ProgressBar) findViewById(R.id.progressBarWardrobe);
progressBarField.setVisibility(View.GONE);
//Creating spinner for select/options for type field
Spinner spinnerType = (Spinner) findViewById(R.id.typeFieldWardrobeScreen);
ArrayAdapter<CharSequence> adapterTypeArray = ArrayAdapter.createFromResource(this, R.array.type_array, android.R.layout.simple_spinner_item);
adapterTypeArray.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerType.setAdapter(adapterTypeArray);
//Creating spinner for select/options for season field
Spinner spinnerSeason = (Spinner) findViewById(R.id.seasonFieldWardrobeScreen);
ArrayAdapter<CharSequence> adapterSeasonArray = ArrayAdapter.createFromResource(this, R.array.season_array, android.R.layout.simple_spinner_item);
adapterSeasonArray.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSeason.setAdapter(adapterSeasonArray);
uploadImageButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//below allows you to open the phones gallery
Image_Picker_Dialog();
}
});
postWardrobe.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//validate input and that something was entered
if(nameField.getText().toString().length()<1 || colorField.getText().toString().length()<1 || sizeField.getText().toString().length()<1 || quantityField.getText().toString().length()<1) {
//missing required info (null was this but lets see)
Toast.makeText(getApplicationContext(), "Please complete all sections!", Toast.LENGTH_LONG).show();
} else {
JSONObject dataWardrobe = new JSONObject();
try {
dataWardrobe.put("type", typeField.getSelectedItem().toString());
dataWardrobe.put("color", colorField.getText().toString());
dataWardrobe.put("season", seasonField.getSelectedItem().toString());
dataWardrobe.put("size", sizeField.getText().toString());
dataWardrobe.put("quantity", quantityField.getText().toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//make progress bar visible
progressBarField.setVisibility(View.VISIBLE);
//execute the post request
new dataSend().postData(dataWardrobe);
}
//below should send data over
}
});
}
// After the selection of image you will retun on the main activity with bitmap image
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Utility.GALLERY_PICTURE)
{
// data contains result
// Do some task
Image_Selecting_Task(data);
} else if (requestCode == Utility.CAMERA_PICTURE)
{
// Do some task
Image_Selecting_Task(data);
}
}
public void Image_Picker_Dialog()
{
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
myAlertDialog.setTitle("Pictures Option");
myAlertDialog.setMessage("Select Picture Mode");
myAlertDialog.setPositiveButton("Gallery", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
Utility.pictureActionIntent = new Intent(Intent.ACTION_GET_CONTENT, null);
Utility.pictureActionIntent.setType("image/*");
Utility.pictureActionIntent.putExtra("return-data", true);
startActivityForResult(Utility.pictureActionIntent, Utility.GALLERY_PICTURE);
}
});
myAlertDialog.setNegativeButton("Camera", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
Utility.pictureActionIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(Utility.pictureActionIntent, Utility.CAMERA_PICTURE);
}
});
myAlertDialog.show();
}
public void Image_Selecting_Task(Intent data)
{
ImageView user_photo = (ImageView) findViewById(R.id.user_photo);
try
{
Utility.uri = data.getData();
if (Utility.uri != null)
{
// User had pick an image.
Cursor cursor = getContentResolver().query(Utility.uri, new String[]
{ android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
cursor.moveToFirst();
// Link to the image
final String imageFilePath = cursor.getString(0);
//Assign string path to File
Utility.Default_DIR = new File(imageFilePath);
// Create new dir MY_IMAGES_DIR if not created and copy image into that dir and store that image path in valid_photo
Utility.Create_MY_IMAGES_DIR();
// Copy your image
Utility.copyFile(Utility.Default_DIR, Utility.MY_IMG_DIR);
// Get new image path and decode it
Bitmap b = Utility.decodeFile(Utility.Paste_Target_Location);
// use new copied path and use anywhere
String valid_photo = Utility.Paste_Target_Location.toString();
b = Bitmap.createScaledBitmap(b, 150, 150, true);
//set your selected image in image view
user_photo.setImageBitmap(b);
cursor.close();
} else
{
Toast toast = Toast.makeText(this, "Sorry!!! You haven't selecet any image.", Toast.LENGTH_LONG);
toast.show();
}
} catch (Exception e)
{
// you get this when you will not select any single image
Log.e("onActivityResult", "" + e);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
//Calling code for different selected menu options
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
//show settings activity screen (main preference activity file)
case R.id.wardrobe:
Intent intent = new Intent(wardrobe.this, wardrobe.class);
startActivity(intent);
//if index button clicked in menu sub-menu options
case R.id.matches:
Toast.makeText(this, "matches was clicked!", 5).show();
//if index button clicked in menu sub-menu options
case R.id.worn:
Toast.makeText(this, "worn was clicked!", 5).show();
default:
}
return super.onOptionsItemSelected(item);
}
private class dataSend extends AsyncTask<JSONObject, Integer, Double> {
protected Double doInBackground(JSONObject... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}
protected void onPostExecute(Double result) {
progressBarField.setVisibility(View.GONE);
Toast.makeText(wardrobe.this, "info sent", Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate(Integer... progress) {
progressBarField.setProgress(progress[0]);
}
public void postData(JSONObject dataWardrobe) {
Log.v("posting data", "poooooost");
// Create a new HttpClient and Post Header
//int TIMEOUT_MILLISEC = 10000; // = 10 seconds
HttpParams httpParams = new BasicHttpParams();
//HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
//HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient httpclient = new DefaultHttpClient(httpParams);
HttpPost httppost = new HttpPost("http://127.0.0.1:3000/wardrobe");
Log.v("posteed", "posteed url");
try {
Log.v("trying data", "prep");
//add data
StringEntity se = new StringEntity( dataWardrobe.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
Log.v("posteed", "posteed 11");
// execute http post request
HttpResponse response = httpclient.execute(httppost);
Log.v("posteed", "posteed 22");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
}
Not sure what I am doing wrong, I tried various things and trying to look up different ways to go about doing this and none of them have worked... maybe it is something more simple than I see... the problem I think lies in the private class within this class.
I haven't read your code in great detail, but I suspect a strong contributor is this:
HttpPost httppost = new HttpPost("http://127.0.0.1:3000/wardrobe");
If you're using the emulator it's probably more likely you want to connect to "10.0.2.2". which is:
Special alias to your host loopback interface (i.e., 127.0.0.1 on your
development machine)
See here for more details on the emulator networking:
http://developer.android.com/tools/devices/emulator.html#emulatornetworking

Categories

Resources