Check duplicate editText before writing into .csv - android

I have several editText in my FirstActivity for CSV:
Button save;
CSV csv;
StringBuffer filePathc;
public final static String EXTRA_MESSAGE = "com.example.mapcard.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_card);
txtName= (EditText) findViewById(R.id.txtName);
txtCompany= (EditText) findViewById(R.id.txtCompany);
txtPhone= (EditText) findViewById(R.id.txtPhone);
txtMobile = (EditText) findViewById(R.id.txtMobile);
txtAddress = (EditText) findViewById(R.id.txtAddress);
txtEmail = (EditText) findViewById(R.id.txtEmail);
txtWebsite = (EditText) findViewById(R.id.txtWebsite);
txtTitle = (EditText) findViewById(R.id.txtTitle);
filePathc = new StringBuffer();
filePathc.append("/sdcard/Android/data/");
file = new File(filePathc+filename.toString());
csv = new CSV(file);
save=(Button)findViewById(R.id.save);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
csv.writeHeader(txtName.getText().toString()+ ","
+txtCompany.getText().toString()
+ "," +txtPhone.getText().toString()
+ "," +txtMobile.getText().toString()
+ "," +txtAddress.getText().toString()
+ "," +txtEmail.getText().toString()
+ "," +txtWebsite.getText().toString()
+ "," +txtTitle.getText().toString());
Intent intent = new Intent(NewCard.this, Template.class);
intent.putExtra("name", Name);
intent.putExtra("company", Company);
intent.putExtra("phone", Phone);
intent.putExtra("mobile", Mobile);
intent.putExtra("address", Address);
intent.putExtra("email", Email);
intent.putExtra("website", Website);
intent.putExtra("title", Title);
startActivity(intent);
SecondActivity is to write this data into .csv file:
public class CSV {
private PrintWriter csvWriter;
private File file;
public CSV(File file) {
this.file = file;
}
public void writeHeader(String data) {
try {
if (data != null) {
csvWriter = new PrintWriter(new FileWriter(file, true));
csvWriter.print("\r\n"+",");
csvWriter.print(data);
csvWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}}
File in directory is successfully created and data is inserted. I am trying to check the data like Name or Email, if it is duplicate/already recorded to not save into .csv and warn user with Toast "same data".
I think it is something to do with line:
try {
if (data != null) {
Your helps and suggestions are appreciated. Thank you.

Use following function
public boolean exist(String newData){
try {
FileInputStream fIn = new FileInputStream(file);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
if(aDataRow.contains(newData))//<--check if data exists
return true;
}
txtData.setText(aBuffer);
myReader.close();
} catch (Exception e) {
}
return false;
}
And change your write header function to:
public void writeHeader(String data) {
try {
if (data != null&&!data.isEmpty()&&!exist(data)) {
csvWriter = new PrintWriter(new FileWriter(file, true));
csvWriter.print("\r\n"+",");
csvWriter.print(data);
csvWriter.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}

data != null doesnt cover the case that the String is just empty, but not null. So basically you get "" from the textview by calling getText(). adding && !"".equals(data) should fix that problem
UPDATE
Well, there is a difference between an empty, and an uninitalized String. An uninitalized String means you declared it like String a; but nothing further.
If you use editText.getText() the editText will return a String which has been initialized but contains only what is currently in it. So basically if there is nothing in the editext it will return "".
And to sum this up:
String a;
null == "" // false
a == null // true
"".equals(editText.getTExt()) // true if the editext doesnt contain anything

Related

Strings mixed up reading from internal storage

I'm using internal storage to store multiple strings entered by the user through multiples edit text.
So the layout is composed of multiples Textviews which correspond to the title of the fields, and multiples Edittexts which correspond to the fields where the user can enter his string.
When the user has finished, he presses the save button and this function is triggered :
public void save(View view) // SAVE
{
File file= null;
String name = editname.getText().toString()+"\n";
String marque = editmarque.getText().toString()+"\n";
String longueur = editlongueur.getText().toString()+"\n";
String largeur = editlargeur.getText().toString()+"\n";
String tirant = edittirant.getText().toString()+"\n";
String immatri = editImmatriculation.getText().toString()+"\n";
String port = editPort.getText().toString()+"\n";
String contact = editContact.getText().toString()+"\n";
String panne = editPanne.getText().toString()+"\n";
String poste = editPoste.getText().toString()+"\n";
String police = editPolice.getText().toString()+"\n";
String assurance = editAssurance.getText().toString();
FileOutputStream fileOutputStream = null;
try {
file = getFilesDir();
fileOutputStream = openFileOutput("Code.txt", Context.MODE_PRIVATE); //MODE PRIVATE
fileOutputStream.write(name.getBytes());
fileOutputStream.write(marque.getBytes());
fileOutputStream.write(longueur.getBytes());
fileOutputStream.write(largeur.getBytes());
fileOutputStream.write(tirant.getBytes());
fileOutputStream.write(immatri.getBytes());
fileOutputStream.write(port.getBytes());
fileOutputStream.write(contact.getBytes());
fileOutputStream.write(panne.getBytes());
fileOutputStream.write(poste.getBytes());
fileOutputStream.write(police.getBytes());
fileOutputStream.write(assurance.getBytes());
Toast.makeText(this, "Saved \n" + "Path --" + file + "\tCode.txt", Toast.LENGTH_SHORT).show();
editname.setText("");
editmarque.setText("");
editlargeur.setText("");
editlongueur.setText("");
edittirant.setText("");
editImmatriculation.setText("");
editPort.setText("");
editContact.setText("");
editPanne.setText("");
editPoste.setText("");
editPolice.setText("");
editAssurance.setText("");
return;
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Than, in another file I retrieve this data through another button that triggers this function :
public void load(View view)
{
try {
FileInputStream fileInputStream = openFileInput("Code.txt");
int read = -1;
StringBuffer buffer = new StringBuffer();
while((read =fileInputStream.read())!= -1){
buffer.append((char)read);
}
fileInputStream.close();
String tab[] = buffer.toString().split("\n");
String boatname = tab[0];
String marque = tab[1];
String longueur = tab[2];
String largeur = tab[3];
String tirant = tab[4];
String immatri = tab[5];
String port = tab[6];
String contact = tab[7];
String panne = tab[8];
String poste = tab[9];
String assurance = tab[10];
String police = tab[11];
getboatname.setText(boatname);
getmarque.setText(marque);
getlongueur.setText(longueur);
getlargeur.setText(largeur);
getTirantdeau.setText(tirant);
getImmatriculation.setText(immatri);
getPort.setText(port);
getContact.setText(contact);
getPanne.setText(panne);
getPoste.setText(poste);
getAssurance.setText(assurance);
getPolice.setText(police);
} catch (Exception e) {
e.printStackTrace();
}
}
So in the save function I'm splitting the entered strings with \n, and I save the file to the internal storage, and in the load function I retrieve the strings using an array and splitting with every \n and I set the text with the correct index.
What I don't understand is that the results are all mixed up, the string of the first field is displayed in the last field for example, why ?
You can Make a Single String and write it. Also, use a different separator. You can use StringBuffer for it.
StringBuffer s=new StringBuffer();
s.append(editname.getText().toString());
s.append("##########");
s.append(editmarque.getText().toString());
s.append("##########");
s.append(editlongueur.getText().toString());
s.append("##########");
s.append(editlargeur.getText().toString());
s.append("##########");
s.append(edittirant.getText().toString());
s.append("##########");
s.append(editPort.getText().toString());
s.append("##########");
s.append(editContact.getText().toString());
s.append("##########");
s.append(editPanne.getText().toString());
s.append("##########");
s.append(editPoste.getText().toString());
s.append("##########");
s.append(editPolice.getText().toString());
s.append("##########");
s.append(editAssurance.getText().toString());
s.append("##########");
FileOutputStream fileOutputStream = null;
try {
file = getFilesDir();
fileOutputStream = openFileOutput("Code.txt", Context.MODE_PRIVATE); //MODE PRIVATE
fileOutputStream.write(s.toString().getBytes());
Toast.makeText(this, "Saved \n" + "Path --" + file + "\tCode.txt", Toast.LENGTH_SHORT).show();
editname.setText("");
editmarque.setText("");
editlargeur.setText("");
editlongueur.setText("");
edittirant.setText("");
editImmatriculation.setText("");
editPort.setText("");
editContact.setText("");
editPanne.setText("");
editPoste.setText("");
editPolice.setText("");
editAssurance.setText("");
return;
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
When you get FileInputStream split the String with this "##########" vlaue

Memory usage increases with every reload of intent in Android. Why?

I have an activity/intent in which a text file (which contains a JSON array) is read from the device.
On every reload another row from the array is being processes.
The text file isn't that large (20 Kb) and is being downloaded in the MainActivity together with some images (up to 50) which are between 20 and 70 Kb.
Everytime the intent is reloaded and another row is processes, another image is being loaded into an ImageView. Also several TextViews are updated with Strings that are read from the JSON array.
The issue is that with every reload of the intent, the memory usage increases with about 1 Mb.
I show this through the use of:
Runtime runtime = Runtime.getRuntime();
long usedMemory=runtime.totalMemory() / (1024 * 1024);
The Bitmap is recycled,
BufferedWriter is closed,
FileInputStream is closed,
BufferedReader is closed and
InputStreamReader is closed
What am I missing that causes the memory usage to increase?
This is the code form the Activity:
public class LoadRaaplijstActivity extends AppCompatActivity {
private TextView locatieText;
private TextView totaalText;
private TextView inhoudText;
private TextView descriptionText;
private TextView eanText;
private TextView ditpadText;
private TableLayout layout16;
private TableLayout layout32;
private Button raapbuttonNext;
private Menu menu;
private Toast toast;
private String next;
private String prev;
private String deze;
private String ean;
private String foto;
private String description;
private String voorraad;
private String totaal;
private String inhoud;
private JSONArray bakken;
private int aantalbakken;
private String einde = "";
private String loadeinde = "0";
private String picked;
private String locatie;
private String locatiepadclean;
private String locatiemeterclean;
private String locatieplankclean;
private String locatievakjeclean;
private String pijl;
private String totaalditpad;
private String batch;
private String kar;
private String raper;
private String afmaken;
String spinneridSelected;
String spinnerkarSelected;
String spinnerraperSelected;
String radioAfmakenSelected;
Bitmap myBitmap;
ArrayList<Integer> gehadArray = new ArrayList<Integer>();
//JSON array
private JSONArray raaplijstresult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
setContentView(R.layout.activity_load_raaplijst);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
findViewById(R.id.productimage).setVisibility(View.GONE);
findViewById(R.id.wificonnectie).setVisibility(View.GONE);
findViewById(R.id.probeeropnieuw).setVisibility(View.GONE);
findViewById(R.id.raapbuttonNext).setVisibility(View.VISIBLE);
findViewById(R.id.raapbuttonPrev).setVisibility(View.VISIBLE);
raapbuttonNext = (Button) findViewById(R.id.raapbuttonNext);
raapbuttonNext.setFocusable(true);
raapbuttonNext.setFocusableInTouchMode(true);
raapbuttonNext.requestFocus();
locatieText = (TextView) findViewById(R.id.locatieText);
totaalText = (TextView) findViewById(R.id.totaalText);
inhoudText = (TextView) findViewById(R.id.inhoudText);
eanText = (TextView) findViewById(R.id.eanText);
ditpadText = (TextView) findViewById(R.id.ditpadTxt);
descriptionText = (TextView) findViewById(R.id.descriptionText);
layout16 = (TableLayout) findViewById(R.id.layout16);
layout32 = (TableLayout) findViewById(R.id.layout32);
Intent intent = getIntent();
spinneridSelected = intent.getStringExtra("spinneridSelected");
spinnerkarSelected = intent.getStringExtra("spinnerkarSelected");
spinnerraperSelected = intent.getStringExtra("spinnerraperSelected");
radioAfmakenSelected = intent.getStringExtra("radioAfmakenSelected");
deze = intent.getStringExtra("load");
batch = spinneridSelected;
kar = spinnerkarSelected;
raper = spinnerraperSelected;
afmaken = radioAfmakenSelected;
if(afmaken.equals("ja")){
deze = getLaatstgehad();
}
Integer gehad = Integer.parseInt(deze.toString());
gehadArray = intent.getIntegerArrayListExtra("gehadArray");
if(!gehadArray.contains(gehad)) {
try {
gehadArray.add(gehad);
} catch (NumberFormatException nfe) {
System.out.println("Could not parse " + nfe);
}
}else{
locatieText.setTextColor(Color.GREEN);
}
saveGehad();
getRaaplijstRegel();
}
private void saveGehad() {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/Raaplijst");
File file = new File(dir, "/gehad.txt");
if(file.exists()) file.delete();
try {
BufferedWriter buf = new BufferedWriter(new FileWriter(file, true));
buf.write(deze.toString());
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private String getLaatstgehad() {
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/Raaplijst");
File file = new File(dir, "/gehad.txt");
String ret = deze;
if(file.exists()){
try {
FileInputStream inputStream = new FileInputStream (file);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStreamReader.close();
bufferedReader.close();
inputStream.close();
String gehadFromFile = stringBuilder.toString();
ret = gehadFromFile;
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else{
ret = deze;
}
return ret;
}
public void loadPrev (View view){
loadRaaplijstPrev();
}
public void loadRaaplijstPrev (){
if (prev.equals("-1")) {
Intent intent = new Intent(this, GratisProducten.class);
Bundle extras = new Bundle();
extras.putString("spinneridSelected", batch);
extras.putString("spinnerkarSelected", kar);
extras.putString("spinnerraperSelected", raper);
extras.putString("radioAfmakenSelected", "nee");
extras.putIntegerArrayList("gehadArray", gehadArray);
intent.putExtras(extras);
startActivity(intent);
finish();
} else {
Intent intent = new Intent(this, LoadRaaplijstActivity.class);
Bundle extras = new Bundle();
extras.putString("load", prev);
extras.putString("spinneridSelected", batch);
extras.putString("spinnerkarSelected", kar);
extras.putString("spinnerraperSelected", raper);
extras.putString("radioAfmakenSelected","nee");
extras.putIntegerArrayList("gehadArray", gehadArray);
intent.putExtras(extras);
startActivity(intent);
finish();
}
}
public void loadBegin (View view){
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
public void loadBegin(){
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
public void loadNext (View view){
loadRaaplijstNext();
}
public void loadRaaplijstNext (){
if (loadeinde.equals("1")) {
loadEnd();
} else {
Intent intent = new Intent(this, LoadRaaplijstActivity.class);
Bundle extras = new Bundle();
extras.putString("spinneridSelected", batch);
extras.putString("spinnerkarSelected", kar);
extras.putString("spinnerraperSelected", raper);
extras.putString("radioAfmakenSelected","nee");
extras.putString("load", next);
extras.putIntegerArrayList("gehadArray", gehadArray);
intent.putExtras(extras);
startActivity(intent);
finish();
}
}
public void loadEnd(){
Intent intent = new Intent(this, EndActivity.class);
Bundle extras = new Bundle();
extras.putString("einde", einde);
extras.putString("load", deze);
extras.putString("spinneridSelected", batch);
extras.putString("spinnerkarSelected", kar);
extras.putString("spinnerraperSelected", raper);
extras.putString("radioAfmakenSelected", "nee");
extras.putIntegerArrayList("gehadArray", gehadArray);
intent.putExtras(extras);
startActivity(intent);
finish();
}
private String readRaaplijstFromFile() {
String ret = "Raaplijst niet gevonden";
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/Raaplijst");
try {
FileInputStream inputStream = new FileInputStream (new File(dir + "/raaplijstJSON.txt"));
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStreamReader.close();
bufferedReader.close();
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ret;
}
private void getRaaplijstRegel(){
String raaplijstJson = readRaaplijstFromFile();
if(raaplijstJson.equals("Raaplijst niet gevonden")){
}else{
try {
JSONObject j = new JSONObject(raaplijstJson);
raaplijstresult = j.getJSONArray(Config.JSON_ARRAY_RAAPLIJST);
getRegel(raaplijstresult);
} catch (JSONException e) {StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
writeExceptionToFile(stacktrace);
e.printStackTrace();
}
}
}
private void getRegel(JSONArray j) {
for (int h = 0; h < j.length(); h++) {
try {
JSONObject sorteerObj = j.getJSONObject(h);
JSONArray sorteer = sorteerObj.getJSONArray("sorteer");
int i = Integer.parseInt(deze);
try {
JSONObject json = sorteer.getJSONObject(i);
einde = json.getString("einde");
loadeinde = json.getString("loadeinde");
if(loadeinde.equals("1")){
loadEnd();
}
ean = json.getString("ean");
eanText.setText("EAN: " + ean);
locatie = json.getString("locatie");
locatieText.setText(locatie);
locatiepadclean = json.getString("locatiepad");
if(locatiepadclean.equals("leeg")){
locatiepadclean = "";
}
locatiemeterclean = json.getString("locatiemeter");
if(locatiemeterclean.equals("leeg")){
locatiemeterclean = "";
}
locatieplankclean = json.getString("locatieplank");
if(locatieplankclean.equals("leeg")){
locatieplankclean = "";
}
locatievakjeclean = json.getString("locatievakje");
if(locatievakjeclean.equals("leeg")){
locatievakjeclean = "";
}
picked = json.getString("picked");
if(picked.equals("1")) {
locatieText.setTextColor(Color.GREEN);
}
foto = json.getString("foto");
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + "/Raaplijst");
File imgFile = new File(dir + "/" + foto);
if(imgFile.exists()){
if (myBitmap != null) {
myBitmap.recycle();
myBitmap = null;
}
myBitmap = decodeFile(imgFile, 231, 231);
ImageView bindImage = (ImageView) findViewById(R.id.productimage);
bindImage.setImageBitmap(myBitmap);
}else{
toast = Toast.makeText(getApplicationContext(), imgFile.toString(), Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 20);
toast.show();
}
findViewById(R.id.loadingPanel).setVisibility(View.GONE);
findViewById(R.id.productimage).setVisibility(View.VISIBLE);
description = json.getString("description");
descriptionText.setText(description);
voorraad = json.getString("voorraad");
aantalbakken = Integer.parseInt(json.getString("aantalbakken"));
if(aantalbakken == 32){
findViewById(R.id.layout16).setVisibility(View.GONE);
findViewById(R.id.layout32).setVisibility(View.VISIBLE);
findViewById(R.id.layout32).setOnTouchListener(new OnSwipeTouchListener(LoadRaaplijstActivity.this) {
public void onSwipeTop() {
}
public void onSwipeRight() {
loadRaaplijstPrev();
}
public void onSwipeLeft() {
loadRaaplijstNext();
}
public void onSwipeBottom() {
}
});
}else{
findViewById(R.id.layout32).setVisibility(View.GONE);
findViewById(R.id.layout16).setVisibility(View.VISIBLE);
findViewById(R.id.layout16).setOnTouchListener(new OnSwipeTouchListener(LoadRaaplijstActivity.this) {
public void onSwipeTop() {
}
public void onSwipeRight() {
loadRaaplijstPrev();
}
public void onSwipeLeft() {
loadRaaplijstNext();
}
public void onSwipeBottom() {
}
});
}
int b = 0;
int[] textViewIds;
int[] bakdrawables;
if(aantalbakken == 32) {
textViewIds = new int[]{R.id.b32, R.id.b33, R.id.b34, R.id.b35, R.id.b36, R.id.b37, R.id.b38, R.id.b39,
R.id.b40, R.id.b41, R.id.b42, R.id.b43, R.id.b44, R.id.b45, R.id.b46, R.id.b47,
R.id.b48, R.id.b49, R.id.b50, R.id.b51, R.id.b52, R.id.b53, R.id.b54, R.id.b55,
R.id.b56, R.id.b57, R.id.b58, R.id.b59, R.id.b60, R.id.b61, R.id.b62, R.id.b63
};
bakdrawables = new int[]{R.drawable.vbbb1, R.drawable.vbbb2, R.drawable.vbbb3, R.drawable.vbbb4, R.drawable.vbbb5, R.drawable.vbbb6, R.drawable.vbbb7, R.drawable.vbbb8,
R.drawable.vbbb9, R.drawable.vbbb10, R.drawable.vbbb11, R.drawable.vbbb12, R.drawable.vbbb13, R.drawable.vbbb14, R.drawable.vbbb15, R.drawable.vbbb16,
R.drawable.vbbb17, R.drawable.vbbb18, R.drawable.vbbb19, R.drawable.vbbb20, R.drawable.vbbb21, R.drawable.vbbb22, R.drawable.vbbb23, R.drawable.vbbb24,
R.drawable.vbbb25, R.drawable.vbbb26, R.drawable.vbbb27, R.drawable.vbbb28, R.drawable.vbbb29, R.drawable.vbbb30, R.drawable.vbbb31, R.drawable.vbbb32
};
}else{
textViewIds = new int[]{R.id.b16, R.id.b17, R.id.b18, R.id.b19,
R.id.b20, R.id.b21, R.id.b22, R.id.b23,
R.id.b24, R.id.b25, R.id.b26, R.id.b27,
R.id.b28, R.id.b29, R.id.b30, R.id.b31
};
bakdrawables = new int[]{R.drawable.vbb1, R.drawable.vbb2, R.drawable.vbb3, R.drawable.vbb4, R.drawable.vbb5, R.drawable.vbb6, R.drawable.vbb7, R.drawable.vbb8,
R.drawable.vbb9, R.drawable.vbb10, R.drawable.vbb11, R.drawable.vbb12, R.drawable.vbb13, R.drawable.vbb14, R.drawable.vbb15, R.drawable.vbb16
};
}
for (int z = 0; z < aantalbakken; z++) {
String prefixbakdrawable = "vbb";
if(aantalbakken == 32){
prefixbakdrawable = "vbbb";
}
Integer inhoudBak = Integer.parseInt(json.getString("b" + z));
if (inhoudBak > 0) {
((TextView) findViewById(textViewIds[z])).setText(inhoudBak.toString());
((TextView) findViewById(textViewIds[z])).setTextColor(Color.WHITE);
findViewById(textViewIds[z]).setBackgroundResource(bakdrawables[z]);
} else {
((TextView) findViewById(textViewIds[z])).setText(" ");
}
}
totaal = json.getString("totaal");
totaalText.setText(totaal);
inhoud = json.getString("inhoud");
inhoudText.setText(inhoud);
prev = json.getString("prev");
next = json.getString("next");
pijl = json.getString("pijl");
if(pijl.equals("left")){
locatieText.setBackgroundResource(R.drawable.left);
}
totaalditpad = json.getString("totaalditpad");
ditpadText.setText(totaalditpad);
if (sorteerObj.has("bakken")) {
bakken = sorteerObj.getJSONArray("bakken");
}
} catch (JSONException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
e.printStackTrace();
}
} catch (JSONException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
String stacktrace = sw.toString();
writeExceptionToFile(stacktrace);
e.printStackTrace();
}
}
}
public static Bitmap decodeFile(File f,int WIDTH,int HIGHT){
try {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
final int REQUIRED_WIDTH=WIDTH;
final int REQUIRED_HIGHT=HIGHT;
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT)
scale*=2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
public void probeerOpnieuw (View v){
loadAgain("ja");
}
public void loadAgain(String doorgaan) {
Intent intent = new Intent(this, LoadRaaplijstActivity.class);
Bundle extras = new Bundle();
extras.putString("load", deze);
extras.putString("spinneridSelected", batch);
extras.putString("spinnerkarSelected", kar);
extras.putString("spinnerraperSelected", raper);
extras.putString("radioAfmakenSelected", doorgaan);
extras.putIntegerArrayList("gehadArray", gehadArray);
intent.putExtras(extras);
startActivity(intent);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_load_raaplijst, menu);
this.menu = menu;
String headerTxtTxt = "Batch: " + batch + "- Kar: " + kar + "- Raper: " + raper;
Runtime runtime = Runtime.getRuntime();
long maxMemory=runtime.maxMemory() / (1024 * 1024);
long usedMemory=(runtime.totalMemory() / (1024 * 1024)) - (runtime.freeMemory() / (1024 * 1024));
if(!Config.DEBUG.equals("")) headerTxtTxt = headerTxtTxt + " MaxMem:" + maxMemory + "Mb CurMem:" + usedMemory;
setTitle(headerTxtTxt);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.stopraaplijst:
Intent intent = new Intent(this, MainActivity.class);
Bundle extras = new Bundle();
intent.putExtras(extras);
startActivity(intent);
finish();
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_DOWN:
loadAgain(radioAfmakenSelected);
return true;
case KeyEvent.KEYCODE_VOLUME_UP:
loadRaaplijstPrev();
return true;
case KeyEvent.KEYCODE_ENTER:
loadRaaplijstNext();
return true;
default:
return true;
}
}
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_DOWN:
case KeyEvent.KEYCODE_BACK:
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_ENTER:
return true;
default:
return true;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
private void writeExceptionToFile(String exception){
File root = android.os.Environment.getExternalStorageDirectory();
String currentDateTimeString = DateFormat.getDateTimeInstance().format(
new Date());
File dir = new File(root.getAbsolutePath() + "/Lograaplijst");
if (!dir.exists()) {
dir.mkdirs();
}
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd_HHmmss");
String formattedDate = df.format(c.getTime());
File file = new File(dir, "log_h_" + formattedDate + "_" + batch + "_" + kar + ".txt");
try {
BufferedWriter buf = new BufferedWriter(new FileWriter(file, true));
buf.append(currentDateTimeString + ":" + exception.toString());
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Activity with two JSONClasses

I have an activity that suppose to use JSON twice. In the first time it works perfectly, but on the second time it seems that the JSON class goes directly to the onPostExecute function without activating the doInBackground function. This is the activity that calls the JSON:
public class Registration extends ActionBarActivity {
public void regis(View view) {
EditText userName = (EditText) findViewById(R.id.userNameTxt);
EditText pass1 = (EditText) findViewById(R.id.PassTxt);
EditText pass2 = (EditText) findViewById(R.id.RePassTxt);
EditText displayName = (EditText) findViewById(R.id.DisplayTxt);
EditText mail = (EditText) findViewById(R.id.eMailTxt);
CheckBox agree = (CheckBox) findViewById(R.id.checkAgree);
TextView err = (TextView) findViewById(R.id.err);
String uName = userName.getText().toString(), pss1 = pass1.getText().toString(),
pss2 = pass2.getText().toString(), disName = displayName.getText().toString(),
eMail = mail.getText().toString();
if ((uName.length() > 0) && (pss1.length() > 0) && (pss2.length() > 0) && (disName.length() > 0)
&& (eMail.length() > 0)) {
if (pss1.equals(pss2)) {
if (agree.isChecked()) {
err.setVisibility(TextView.INVISIBLE);
String str = "?uname=" + uName;
new JSONClass(this, 2, str, this).execute();
} else {
err.setText("You must approve the use terms");
err.setVisibility(TextView.VISIBLE);
}
} else {
err.setText("The two passwords must match!");
err.setVisibility(TextView.VISIBLE);
}
} else {
err.setText("You must insert values in every cell");
err.setVisibility(TextView.VISIBLE);
}
}
public void checkExist(JSONArray ans) {
try {
int cnt = Integer.parseInt(ans.getJSONObject(0).getString("cnt"));
if (cnt == 1) {
TextView err = (TextView) findViewById(R.id.err);
err.setText("User name already exists!");
err.setVisibility(TextView.VISIBLE);
} else {
EditText userName = (EditText) findViewById(R.id.userNameTxt);
EditText pass = (EditText) findViewById(R.id.PassTxt);
EditText displayName = (EditText) findViewById(R.id.DisplayTxt);
EditText mail = (EditText) findViewById(R.id.eMailTxt);
String uName = userName.getText().toString(), pss = pass.getText().toString(),
disName = displayName.getText().toString(), eMail = mail.getText().toString();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss yyyy-MM-dd");
String currentDateandTime = sdf.format(new Date());
String str = "?uname=" + uName + "&password=" + pss + "&email=" + eMail + "&disnam=" +
disName + "&dt=" + currentDateandTime;
Log.e("log_tag", "Just for me: " + str);
new JSONClass(this, 3, str, this).execute();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void openLogin() {
Intent intent = new Intent(this, Login.class);
startActivity(intent);
finish();
}
}
I removed unnecessary functions. This is my JSON class:
public class JSONClass extends AsyncTask<String,Void,JSONArray>{
private String link;
private int flag;
private Login log = null;
private Registration reg = null;
private Context context;
public JSONClass(Context context, int queryNo, String params, Registration regg) {
this.context = context;
link = "http://pickupfriend.fulba.com/android_project/query" + queryNo + ".php" + params;
reg = regg;
flag = queryNo;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
protected JSONArray doInBackground(String... arg0) {
JSONArray arr = new JSONArray();
try{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(link);
post.addHeader("Content-Type", "application/x-www-form-urlencoded");
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "utf-8");
arr = new JSONArray(result);
}catch(Exception e){
}
return arr;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
public void onPostExecute(JSONArray result) {
switch (flag) {
case 1:
log.getResults(result);
break;
case 2:
reg.checkExist(result);
break;
case 3:
reg.openLogin();
break;
default:
break;
}
}
}
At first I activate the regis function that works perfectly with the json class. Afterwards it suppose to activate checkExist if the cnt parameter is 0, which is 0. Then it is suppose to activate the json class again but it seems that it goes directly to openLogin function without going to the php file and activating it. Am I doing something wrong?

getting images saved in null folder : Android

String gender;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
mTextureView = (TextureView) findViewById(R.id.textureView1);
mTextureView.setSurfaceTextureListener(this);
final Button buttonStartCameraPreview = (Button)findViewById(R.id.startcamerapreview);
final Button buttonCapturePreview = (Button)findViewById(R.id.Capturecamerapreview);
rgGender = (RadioGroup) findViewById(R.id.rgGender);
rdbMale = (RadioButton) findViewById(R.id.rdbMale);
rdbFemale = (RadioButton) findViewById(R.id.rdbFemale);
PatientInfo = (EditText) findViewById(R.id.PatientName);
PatientInfo.setHint("Enter patient name");
PatientAge = (EditText) findViewById(R.id.Age);
PatientAge.setHint("Age");
PatientId = (EditText) findViewById(R.id.PatientId);
PatientId.setHint("Enter patient Id no:");
rawCallback = new PictureCallback()
{
public void onPictureTaken(byte[] data, Camera camera)
{
Log.d("Log", "onPictureTaken - raw");
}
};
shutterCallback = new ShutterCallback()
{
public void onShutter() {
Log.i("Log", "onShutter'd");
}
};
jpegCallback = new PictureCallback()
{
#Override
public void onPictureTaken(byte[] data, Camera mCamera)
{
int imageNum = 0;
String Name = PatientInfo.getText().toString();
String Age = PatientAge.getText().toString();
String Id = PatientId.getText().toString();
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
Date d = new Date();
CharSequence s = DateFormat.format("MM-dd-yy hh-mm-ss", d.getTime());
Rname = "Raw"+s.toString() + "_img_"+ String.valueOf(imageNum)+".jpg";
Pname = "Proc"+s.toString()+ "_img_"+ String.valueOf(imageNum) +".jpg";
File imagesFolders = new File(Environment.getExternalStorageDirectory().toString() + "/" + Name + Age + gender +Id);
imagesFolders.mkdirs();
File output = new File(imagesFolders, Rname);
while (output.exists()){
imageNum++;
Rname = "Raw"+s.toString() + "_img_"+ String.valueOf(imageNum) +".jpg";
Pname = "Proc"+s.toString() + "_img_"+ String.valueOf(imageNum) +".jpg";
output = new File(imagesFolders, Rname);
}
callname ="/sdcard/"+ Name + Age + gender + Id +"/"+ Rname;
Uri uriSavedImage = Uri.fromFile(output);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriSavedImage);
imageFileOS.write(data);
imageFileOS.flush();
imageFileOS.close(); }
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{}
Log.d("Log", "onPictureTaken - jpeg");
}
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId())
{
case R.id.rdbMale:
if (checked)
gender= "M";
rdbFemale.setChecked(false);
break;
case R.id.rdbFemale:
if (checked)
gender = "F";
rdbMale.setChecked(false);
break;
}
}
This is a piece of code. Am trying to save the images in the folder after enter the details like name, age, gender. but if i am not entering any thing and just take the image it will save the image into a null folder. I dont want this to happen. When details are not entered it should not save the image any where and it should show a message like please enter the data. Can anyone help why it is saving the data yo a null folder
Use Validation bro.
if (edt.getText().toString().length() <= 0) {
edt.setError("Please Enter Name/Name Required.");
valid_name = null;
} else if (!edt.getText().toString().matches("[a-zA-Z ]+")) {
edt.setError("Accept Alphabets Only.");
valid_name = null;
} else {
valid_name = edt.getText().toString();
}
or refer this site:
http://chintankhetiya.wordpress.com/2013/05/29/edit-text-validation/

Why can't I update my EditText in onPostExecute with Geocoder in the AsyncTask?

I am trying to reverse geocode inside an AsyncTask to get the address of the current location. I want to set the EditText to the address as default when starting the activity. My problem is I am unable to do this in onPostExecute(), however, I can do it in runOnUiThread() inside doInBackground(). Why is this?
AsyncTask:
protected String doInBackground(Void ...params) {
Geocoder geocoder = new Geocoder(AddSpot.this, Locale.getDefault());
List<Address> addresses = null;
try {
// Call the synchronous getFromLocation() method by passing in the lat/long values.
addresses = geocoder.getFromLocation(currentLat, currentLng, 1);
}
catch (IOException e)
{
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
// Format the first line of address (if available), city, and country name.
final String addressText = String.format("%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality(),
address.getCountryName());
System.out.println(addressText);
return addressText;
}
return null;
}
protected void onPostExecute(String address) {
EditText addrField=(EditText)findViewById(R.id.addr);
addrField.setText(address);
}
That does not work. However, when I stick a runOnUiThread in it, it works:
if (addresses != null && addresses.size() > 0)
{
Address address = addresses.get(0);
// Format the first line of address (if available), city, and country name.
final String addressText = String.format("%s, %s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getLocality(),
address.getCountryName());
runOnUiThread(new Runnable()
{
#Override
public void run()
{
EditText addrField=(EditText)findViewById(R.id.addr);
addrField.setText(addressText);
}
});
System.out.println(addressText);
return addressText;
}
UPDATE
After some debugging it appears that onPostExecute is never called at all no matter what I do.
Things I have tried:
Log information inside onPostExecute: Does not appear
Remove the entire logic inside doInBackground so it's like this return "hello" : onPost still does not execute
You did not put #Override above onPostExecute. Also asynctask object must to be created inside UI thread.
EDIT: Your edittextis not updated, becauseit is consumedimidiatly after post execute is finished.
1) write EditText addrField; as class variable of activity class.
2) find reference to it in onCreate().
3) on your original onpostexecute should remain only addrField.setText(address);
there is my class, where textfields are updated from onPostexecute without any problems
public class AddToCheckActivity extends Activity {
// All static variables
private ProgressDialog pd = null;
// XML node keys
TextView active;
String addId = "";
JSONObject json = null;
ListView list;
String not_id, not_section, not_street, not_sqTotal, not_sqLiving,
not_sqKitchen, not_flat, not_floor, not_floors, not_text,
user_phone1, user_phone2, user_contact, not_region, not_district,
not_settle, not_price, not_photo, not_date, not_date_till, not_up,
not_premium, not_status, region_title, district_title,
settle_title, section_title, not_priceFor;
LinearLayout lin;
ImageView photo1;
ImageView photo2;
ImageView photo3;
Activity app;
ArrayList<String> photo_ids = new ArrayList<String>();
TextView address;
TextView date;
TextView date_till;
TextView description;
TextView district;
TextView flat;
TextView floor;
TextView floors;
TextView id;
TextView phone1;
TextView phone2;
TextView premium;
TextView region;
TextView section;
TextView settle;
TextView sqKitchen;
TextView sqLiving;
TextView sqTotal;
TextView uped;
TextView price;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aadd_addtocheck);
app = this;
lin = (LinearLayout) findViewById(R.id.lin);
address = (TextView) findViewById(R.id.tv_atc_address);
date = (TextView) findViewById(R.id.tv_atc_date);
date_till = (TextView) findViewById(R.id.tv_atc_date_till);
description = (TextView) findViewById(R.id.tv_atc_description);
district = (TextView) findViewById(R.id.tv_atc_dstrict);
flat = (TextView) findViewById(R.id.tv_atc_flat);
floor = (TextView) findViewById(R.id.tv_atc_floor);
floors = (TextView) findViewById(R.id.tv_atc_floors);
id = (TextView) findViewById(R.id.tv_atc_id);
phone1 = (TextView) findViewById(R.id.tv_atc_phone1);
phone2 = (TextView) findViewById(R.id.tv_atc_phone2);
premium = (TextView) findViewById(R.id.tv_atc_premium);
region = (TextView) findViewById(R.id.tv_atc_region);
section = (TextView) findViewById(R.id.tv_atc_section);
settle = (TextView) findViewById(R.id.tv_atc_settle);
sqKitchen = (TextView) findViewById(R.id.tv_atc_sqKitchen);
sqLiving = (TextView) findViewById(R.id.tv_atc_sqLiving);
sqTotal = (TextView) findViewById(R.id.tv_atc_sqTotal);
uped = (TextView) findViewById(R.id.tv_atc_uped);
price = (TextView) findViewById(R.id.tv_atc_price);
Bundle ex = getIntent().getExtras();
Log.d("Gues: ", "1");
Button back_button = (Button) findViewById(R.id.back_btn);
back_button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(),
ChooserActivity.class);
startActivity(i);
finish();
}
});
pd = new ProgressDialog(app);
pd.setOwnerActivity(app);
pd.setTitle("Идет загрузка...");
pd.setCancelable(true);
if (ex != null) {
addId = ex.getString("add_id");
Log.d("Gues: ", "2");
not_id = not_priceFor = not_section = not_street = not_sqTotal = not_sqLiving = not_sqKitchen = not_flat = not_floor = not_floors = not_text = user_phone1 = user_phone2 = user_contact = not_region = not_district = not_settle = not_price = not_photo = not_date = not_date_till = not_up = not_premium = not_status = region_title = district_title = settle_title = section_title = "";
Log.d("Gues: ", "3");
GetAdd addvert = new GetAdd();
addvert.execute();
}
}
public void onClickBtnAtcDelete(View v) {
Thread t = new Thread(new Runnable() {
public void run() {
UserFunctions u = new UserFunctions();
u.deleteAdd(not_id);
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent i = new Intent(getApplicationContext(), MyAddActivity.class);
startActivity(i);
finish();
}
public void btnAtcEdit(View v) {
Intent i = new Intent(getApplicationContext(), AddSaveActivity.class);
final BitmapDrawable bitmapDrawable1 = (BitmapDrawable) photo1
.getDrawable();
final Bitmap yourBitmap1 = bitmapDrawable1.getBitmap();
ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
yourBitmap1.compress(Bitmap.CompressFormat.PNG, 90, stream1);
byte[] imm1 = stream1.toByteArray();
final BitmapDrawable bitmapDrawable2 = (BitmapDrawable) photo2
.getDrawable();
final Bitmap yourBitmap2 = bitmapDrawable2.getBitmap();
ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
yourBitmap2.compress(Bitmap.CompressFormat.PNG, 90, stream2);
byte[] imm2 = stream2.toByteArray();
final BitmapDrawable bitmapDrawable3 = (BitmapDrawable) photo3
.getDrawable();
final Bitmap yourBitmap3 = bitmapDrawable3.getBitmap();
ByteArrayOutputStream stream3 = new ByteArrayOutputStream();
yourBitmap3.compress(Bitmap.CompressFormat.PNG, 90, stream3);
byte[] imm3 = stream3.toByteArray();
i.putExtra("photo1", imm1);
i.putExtra("photo2", imm2);
i.putExtra("photo3", imm3);
i.putStringArrayListExtra("photo_ids", photo_ids);
i.putExtra("not_id", not_id);
i.putExtra("not_section", not_section);
i.putExtra("not_street", not_street);
i.putExtra("not_sqTotal", not_sqTotal);
i.putExtra("not_sqLiving", not_sqLiving);
i.putExtra("not_sqKitchen", not_sqKitchen);
i.putExtra("not_flat", not_flat);
i.putExtra("not_floor", not_floor);
i.putExtra("not_floors", not_floors);
i.putExtra("not_text", not_text);
i.putExtra("not_phone1", user_phone1);
i.putExtra("not_phone2", user_phone2);
i.putExtra("not_region", not_region);
i.putExtra("not_district", not_district);
i.putExtra("not_settle", not_settle);
i.putExtra("not_price", not_price);
i.putExtra("not_date", not_date);
i.putExtra("not_date_till", not_date_till);
i.putExtra("region_title", region_title);
i.putExtra("district_title", district_title);
i.putExtra("section_title", section_title);
i.putExtra("settle_title", settle_title);
i.putExtra("not_priceFor", not_priceFor);
startActivity(i);
}
public void onClickAtcGoToChooser(View v) {
Intent i = new Intent(getApplicationContext(), MyAddActivity.class);
startActivity(i);
finish();
}
class GetAdd extends AsyncTask<Integer, Void, JSONObject> {
// private ProgressDialog pd = null;
private int op = 0;
#Override
protected void onPreExecute() {
// pd = new ProgressDialog(app);
// pd.setOwnerActivity(app);
// pd.setTitle("Идет загрузка...");
// pd.setCancelable(true);
pd.show();
}
#Override
protected JSONObject doInBackground(Integer... params) {
// TODO Auto-generated method stub
UserFunctions u = new UserFunctions();
// json = u.getNewAdd(addId);
return u.getNewAdd(addId);
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
pd.dismiss();
active = (TextView) findViewById(R.id.tv_atc_active);
photo1 = (ImageView) findViewById(R.id.imageP1);
photo2 = (ImageView) findViewById(R.id.imageP2);
photo3 = (ImageView) findViewById(R.id.imageP3);
ImageLoader imi = new ImageLoader(app.getApplicationContext());
if (result != null && result.has("not_id")) {
try {
Log.d("Gues: ",
"5_1 to status " + result.getString("not_status"));
// active.setText(json.getString("not_status")+"");
not_status = ("" + result.getString("not_status"));
not_region = ("" + result.getString("not_region"));
not_district = ("" + result.getString("not_district"));
not_settle = ("" + result.getString("not_settle"));
not_section = ("" + result.getString("not_section"));
not_street = (result.getString("not_street"));
not_date = (result.getString("not_date"));
not_price = (result.getString("not_price"));
not_date_till = (result.getString("not_date_till"));
not_text = (result.getString("not_text"));
district_title = (result.getString("district_title"));
not_flat = (result.getString("not_flat"));
not_floor = (result.getString("not_floor"));
not_floors = (result.getString("not_floors"));
not_id = (result.getString("not_id"));
user_phone1 = (result.getString("user_phone1"));
user_phone2 = (result.getString("user_phone2"));
not_premium = (result.getString("not_premium"));
region_title = (result.getString("region_title"));
section_title = (result.getString("section_title"));
settle_title = (result.getString("settle_title"));
not_sqKitchen = (result.getString("not_sqKitchen"));
not_sqTotal = (result.getString("not_sqTotal"));
not_sqLiving = (result.getString("not_sqLiving"));
not_up = (result.getString("not_up"));
LinearLayout l = (LinearLayout) findViewById(R.id.appDetail);
if (Integer.parseInt(not_section) == 1981
|| Integer.parseInt(not_section) == 1982) {
l.setVisibility(View.GONE);
}
not_priceFor = (result.getString("not_priceFor"));
String link1, link2, link3;
link1 = link2 = link3 = "";
JSONArray ar = result.getJSONArray("not_photos");
JSONArray pp = result.getJSONArray("photo_ids");
Log.d("ATC photo_ids", "-" + pp.length());
Log.d("ATC result", result.toString());
Log.d("ATC result pp", pp.toString());
Log.d("ATC result ppelement", pp.getString(0).toString());
for (int i = 0; i < pp.length(); i++) {
Log.d("ATC photo_ids pos", "-" + i);
Log.d("ATC result ppelement iter", pp.getString(i)
.toString());
photo_ids.add(pp.getString(i).toString());
}
// String[] ph = new String[3];
// for (int i =0; i< 3;i++){
// ph[i]=ar.getJSONObject(i).toString();
// }
imi.DisplayImage(ar.getString(0).toString(), photo1);
imi.DisplayImage(ar.getString(1).toString(), photo2);
imi.DisplayImage(ar.getString(2).toString(), photo3);
Log.d("Gues: ", "5_5");
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (Integer.parseInt(not_status) == 0) {
active.setText("Неактивно");
} else {
active.setText("Активно");
}
address.setText("Улица: " + not_street);
date.setText("Создано: " + not_date);
date_till.setText("Действительно до: " + not_date_till);
description.setText("Подробности объявления: " + "\n"
+ not_text);
district.setText("Город/поселок: " + district_title);
if (Integer.parseInt(not_section) == 1981
|| Integer.parseInt(not_section) == 1982) {
flat.setText("Машиномест: " + not_flat);
} else
flat.setText("Количество комнат: " + not_flat);
floor.setText("Этаж: " + not_floor);
floors.setText("Этажность: " + not_floors);
id.setText("ID: " + not_id + " ");
phone1.setText("Телефон: " + user_phone1);
phone2.setText("Телефон: " + user_phone2);
if (Integer.parseInt(not_premium) == 0) {
premium.setText("Обычное");
} else {
premium.setText(" Примиумное");
}
region.setText("Регион: " + region_title);
section.setText("В рубрике: " + section_title);
settle.setText("Район: " + settle_title);
sqKitchen.setText("Площадь кухни: " + not_sqKitchen);
sqTotal.setText("Общая площадь: " + not_sqTotal);
sqLiving.setText("Жилая площадь: " + not_sqLiving);
if (Integer.parseInt(not_up) == 0) {
uped.setText("");
} else {
uped.setText(" Поднятое ");
}
String priceT = "";
if (Integer.parseInt(not_priceFor) == 1)
priceT = "за все";
else if (Integer.parseInt(not_priceFor) == 2)
priceT = "за кв.м";
else if (Integer.parseInt(not_priceFor) == 3)
priceT = "за месяц";
else if (Integer.parseInt(not_priceFor) == 4)
priceT = "в сутки";
else if (Integer.parseInt(not_priceFor) == 5)
priceT = "в час";
else if (Integer.parseInt(not_priceFor) == 6)
priceT = "за кв.м./месяц";
else if (Integer.parseInt(not_priceFor) == 7)
priceT = "за сотку";
price.setText("Цена: " + not_price + " грн. " + priceT);
lin.setVisibility(View.VISIBLE);
} else {
error();
}
}
}
}
PS: t oavoid problems in future, don't put UI operations in any part of try{}

Categories

Resources