Firebase error cannot get into the database - android

//error here
private FirebaseDatabase database = FirebaseDatabase.getInstance();
private DatabaseReference myRef = database.getReference("Runtime");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ping);
btn1 = (Button) findViewById(R.id.ping);
lstPing = (ListView) findViewById(R.id.listPing);
editText = (EditText) findViewById(R.id.edit_query);
// Write a message to the database
}
public void fExecutePing (View view) {
Editable host = editText.getText();
List<String> listResponsPing = new ArrayList<String>();
ArrayAdapter<String> adapterList = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listResponsPing);
try {
String cmdPing = "ping -c 2 "+host;
Runtime r = Runtime.getRuntime();
Process p = r.exec(cmdPing);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String inputLine;
String time_part = "";
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
while ((inputLine = in.readLine())!= null){
for(String time:listResponsPing){
if(time.contains("time=")){
String[] parts = time.split("time\\=");
time_part = parts[1];
myRef.push().setValue(time_part + " " + dateFormat.format(date));
}
}
listResponsPing.add(inputLine);
lstPing.setAdapter(adapterList);
}
Toast.makeText(this, " Command Execute Success", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, " Error: "+e.getMessage().toString(), Toast.LENGTH_SHORT).show();
}
}
}
I'm new in firebase and android. My apps are about network testing. I have a problem in my PingActivity. I cannot insert the result from ping activity to Firebase. I've tried all the solution that I found. But its not working. Please help. Thank you.
The error at the code that I've comment.

Related

Spinner - How to get value? Android Studio

I would like to insert values from a form into my database. I had problems with values from spinners and I did something wrong, because when I intent in my next activity where the form is the app stops. I will be really grateful.
MainActivity.java
public class MainActivity extends AppCompatActivity {
EditText UsernameEt, PasswordEt;
private static Button btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
UsernameEt = (EditText) findViewById(R.id.etUserName);
PasswordEt = (EditText) findViewById(R.id.etPassword);
OnClickButtonListener();
}
public void OnClickButtonListener() {
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLogin.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(".SecondPan");
startActivity(intent);
}
}
);
}
public void OnLogin(View view)
{
String username = UsernameEt.getText().toString();
String password = PasswordEt.getText().toString();
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type,username,password);
}
public void OpenReg(View view){
startActivity(new Intent(this,Register.class));
}
}
Second Panel where user should've been intented and where spinners are:
public class SecondPan extends AppCompatActivity implements AdapterView.OnItemClickListener {
private Spinner sspnOption6, sspn2;
private TextView ttxOption6, ttx;
EditText umowa,nazwa,kategorie,opis,zabezpieczenia,dane;
String czy_dane, transfer;
#SuppressLint("CutPasteId")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second_pan);
Spinner sspn2 = (Spinner)findViewById(R.id.sspn);
czy_dane = sspn2.getSelectedItem().toString();
Spinner sspnOption6 = (Spinner)findViewById(R.id.sspn2);
transfer = sspnOption6.getSelectedItem().toString();
umowa = (EditText) findViewById(R.id.scnd_txt1);
nazwa = (EditText) findViewById(R.id.scnd_txt2);
kategorie = (EditText) findViewById(R.id.scnd_txt3);
opis = (EditText) findViewById(R.id.scnd_tx4);
zabezpieczenia = (EditText) findViewById(R.id.scnd_tx6);
dane = (EditText) findViewById(R.id.scnd_tx7);
sspnOption6 = findViewById(R.id.sspn);
ArrayAdapter<CharSequence> FirstAdapter = ArrayAdapter.createFromResource(this, R.array.tab1, android.R.layout.simple_spinner_item);
FirstAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sspn2=findViewById(R.id.sspn2);
ArrayAdapter<CharSequence> Secondadapter = ArrayAdapter.createFromResource(this, R.array.transfer, android.R.layout.simple_spinner_item);
Secondadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sspn2.setAdapter(Secondadapter);
}
public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
String text = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), text, Toast.LENGTH_SHORT).show();
}
public void OnInsert(View view ) {
String str_czy_dane = sspn2.getSelectedItem().toString();
String str_umowa = umowa.getText().toString();
String str_nazwa = nazwa.getText().toString();
String str_kategorie = kategorie.getText().toString();
String str_opis = opis.getText().toString();
String str_transfer = sspn2.getSelectedItem().toString();
String str_zabezpieczenia = zabezpieczenia.getText().toString();
String str_dane = dane.getText().toString();
String type = "insert";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, str_czy_dane,str_umowa, str_nazwa, str_kategorie, str_opis,str_transfer, str_zabezpieczenia, str_dane);
}
}
And there is a script to POST data:
BackgroundWorker.java
else if(type.equals("insert")){
try {
String umowa = params[1];
String czy_dane = params[2];
String nazwa = params[3];
String kategorie = params[4];
String opis = params[5];
String transfer = params[6];
String zabezpieczenia = params[7];
String dane = params[8];
URL url = new URL (insert_url);
HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String post_data = URLEncoder.encode("czy_dane","UTF-8")+"="+URLEncoder.encode(czy_dane,"UTF-8")+"&"+
URLEncoder.encode("umowa","UTF-8")+"="+URLEncoder.encode(umowa,"UTF-8")+"&"
+URLEncoder.encode("nazwa","UTF-8")+"="+URLEncoder.encode(nazwa,"UTF-8")+"&"
+URLEncoder.encode("kategorie","UTF-8")+"="+URLEncoder.encode(kategorie,"UTF-8")+"&"
+URLEncoder.encode("opis","UTF-8")+"="+URLEncoder.encode(opis,"UTF-8")+"&"
+URLEncoder.encode("transfer","UTF-8")+"="+URLEncoder.encode(transfer,"UTF-8")+"&"
+URLEncoder.encode("zabezpieczenia","UTF-8")+"="+URLEncoder.encode(zabezpieczenia,"UTF-8")+"&"
+URLEncoder.encode("dane","UTF-8")+"="+URLEncoder.encode(dane,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1")) ;
String result="";
String line="";
while((line = bufferedReader.readLine())!=null) {
result+= line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
In your code, you are twice assigning Spinner.
Spinner sspn2 = (Spinner)findViewById(R.id.sspn); /// FIRST SPINNER 1 time
czy_dane = sspn2.getSelectedItem().toString();
Spinner sspnOption6 = (Spinner)findViewById(R.id.sspn2);/// SECOND SPINNER 1 time
transfer = sspnOption6.getSelectedItem().toString();
umowa = (EditText) findViewById(R.id.scnd_txt1);
nazwa = (EditText) findViewById(R.id.scnd_txt2);
kategorie = (EditText) findViewById(R.id.scnd_txt3);
opis = (EditText) findViewById(R.id.scnd_tx4);
zabezpieczenia = (EditText) findViewById(R.id.scnd_tx6);
dane = (EditText) findViewById(R.id.scnd_tx7);
sspnOption6 = findViewById(R.id.sspn); /// FIRST SPINNER 2 time
ArrayAdapter<CharSequence> FirstAdapter = ArrayAdapter.createFromResource(this, R.array.tab1, android.R.layout.simple_spinner_item);
FirstAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sspn2=findViewById(R.id.sspn2); /// SECOND SPINNER 2 time
ArrayAdapter<CharSequence> Secondadapter = ArrayAdapter.createFromResource(this, R.array.transfer, android.R.layout.simple_spinner_item);
Secondadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sspn2.setAdapter(Secondadapter);
SOLUTION:
Spinner sspn2 ;
Spinner sspnOption6 ;
umowa = (EditText) findViewById(R.id.scnd_txt1);
nazwa = (EditText) findViewById(R.id.scnd_txt2);
kategorie = (EditText) findViewById(R.id.scnd_txt3);
opis = (EditText) findViewById(R.id.scnd_tx4);
zabezpieczenia = (EditText) findViewById(R.id.scnd_tx6);
dane = (EditText) findViewById(R.id.scnd_tx7);
sspnOption6 = findViewById(R.id.sspn);
ArrayAdapter<CharSequence> FirstAdapter = new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_item, getResources()
.getStringArray(R.array.tab1));
FirstAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sspnOption6.setAdapter(FirstAdapter);
sspn2=findViewById(R.id.sspn2);
ArrayAdapter<CharSequence> Secondadapter = new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_item, getResources()
.getStringArray(R.array.transfer));
Secondadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sspn2.setAdapter(Secondadapter);
czy_dane = sspn2.getSelectedItem().toString();
transfer = sspnOption6.getSelectedItem().toString();

Spinner is not populating with the data recieved from webservice

I am creating an android application for my client and in this app the user have to fill a form. I am using JSON web service for this purpose and I know how to send and receive data. Problem is that while I am fetching necessary data to fill the form and populating the spinner (I have multiple spinners in my form) the data doesn't populate to the spinner however I am successfully getting the data from web service. Please review my code and kindly help me because i don't have much time remaining. Thanks in advance.
public class AgentActivity extends AppCompatActivity {
Spinner spnr_commodity;
public Spinner spnr_ImpExp;
public Spinner spnr_unit;
public Spinner spnr_terminal;
public Spinner spnr_eta;
public Spinner spnr_lastport;
private String TAG = "Agent";
private TextView txtName_L;
private TextView txtName;
private TextView txtloa;
private TextView txtbeam;
private TextView txtgrt;
private TextView txtnrt;
private TextView txtpcno;
private ImageButton btnSearch;
private SearchView shipSearch;
private String strShipName = "Select Ship Name";
private String str_qty;
private AlphaAnimation buttonClick = new AlphaAnimation(1F, 0.8F);
/*private AnimationSet edtQty = new AnimationSet();*/
EditText a_date;
EditText d_date;
EditText a_time;
EditText qty;
DatePickerDialog datePickerDialog1;
DatePickerDialog datePickerDialog2;
TimePickerDialog timePickerDialog;
ProgressDialog progressDialog;
Toolbar mToolbar;
public String [] arr_impexp= {"Type","Import","Export"};
public String[] arr_lastport={"Select ","KPT","Singapore","China","Dubai","Indonesia","Korea"};
public String[] arr_shipname ;
public String[] arr_terminal;
public String [] arr_commodity ;
ArrayAdapter<String> unitAdapter;
ArrayAdapter<String> terminalAdapter;
ArrayAdapter<String> commodityAdapter;
ArrayAdapter<String> ImpExpAdapter;
ArrayAdapter<String> lastportAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences preference = getApplication().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
setTitle(preference.getString("nameKey", null));
setContentView(R.layout.agent_activity);
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
mToolbar.setTitleTextColor(Color.WHITE);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
txtName_L = (TextView) findViewById(R.id.l_shipName);
txtName = (TextView) findViewById(R.id.n_ship);
txtloa = (TextView) findViewById(R.id.loa);
txtbeam = (TextView) findViewById(R.id.beam);
txtgrt = (TextView) findViewById(R.id.grt);
txtnrt = (TextView) findViewById(R.id.nrt);
txtpcno = (TextView) findViewById(R.id.pc);
btnSearch = (ImageButton) findViewById(R.id.btnsearch);
qty = (EditText) findViewById(R.id.c_qty);
a_date = (EditText) findViewById(R.id.a_date);
d_date = (EditText) findViewById(R.id.d_date);
a_time = (EditText) findViewById(R.id.a_time);
spnr_ImpExp = (Spinner) findViewById(R.id.spnr_ImpExp);
spnr_ImpExp.setPrompt("Type");
spnr_unit = (Spinner) findViewById(R.id.spnr_unit);
spnr_terminal = (Spinner) findViewById(R.id.spnr_terminal);
spnr_eta = (Spinner) findViewById(R.id.spnr_eta);
spnr_lastport = (Spinner) findViewById(R.id.spnr_lastport);
//download data from php
new DownloadInitialInformation().execute("http://192.168.1.131/pqamssql/agent.php");
txtName_L.setText(strShipName);
List<String> list = new ArrayList<>();
list.add("Select Unit ");
list.add("TUE");
list.add("M.Ton");
list.add("C.Met");
list.add("Units");
unitAdapter = new ArrayAdapter<String>(this,R.layout.spinner_item, list);
unitAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
spnr_unit.setAdapter(unitAdapter);
ImpExpAdapter = new ArrayAdapter<String>(this, R.layout.spinner_item, arr_impexp);
ImpExpAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
spnr_ImpExp.setAdapter(ImpExpAdapter);
txtName_L.setText(strShipName);
// str_qty = qty.getText().toString();
// Toast.makeText(this,"QTY: "+str_qty,Toast.LENGTH_SHORT).show();
txtName.setText("SHIP NAME | " + Constants.getShipName());
if (!Constants.getShipName().equals(" ")) {
Log.i(TAG, "Ship Name : " + Constants.getShipName());
new ShipDetail().execute("http://192.168.1.131/pqamssql/initial.php?shipname=" + Constants.getShipName());
}
spnr_unit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position != 0) {
Toast.makeText(parent.getContext(),
"Position: " + position + " OnItemSelectedListener : " + parent.getItemAtPosition(position).toString(),
Toast.LENGTH_SHORT).show();
String str_craftType = parent.getItemAtPosition(position).toString();
//craft.setText(str_craftType);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// v.startAnimation(buttonClick);
Intent i = new Intent(AgentActivity.this, AgentListView.class);
startActivity(i);
}
});
// initiate the date picker and a button
// perform click event on edit text
a_date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// calender class's instance and get current date , month and year from calender
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR); // current year
int mMonth = c.get(Calendar.MONTH); // current month
int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
// date picker dialog
datePickerDialog1 = new DatePickerDialog(AgentActivity.this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
a_date.setText(dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog1.show();
}
});
d_date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// calender class's instance and get current date , month and year from calender
final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR); // current year
int mMonth = c.get(Calendar.MONTH); // current month
int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
// date picker dialog
datePickerDialog2 = new DatePickerDialog(AgentActivity.this,R.style.agentTheme,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
d_date.setText(dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog2.show();
}
});
a_time.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Calendar c = Calendar.getInstance();
// Get the current hour and minute
int hour = c.get(Calendar.HOUR_OF_DAY);
int mint = c.get(Calendar.MINUTE);
timePickerDialog = new TimePickerDialog(AgentActivity.this,R.style.AppTheme_Light_Dialog, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
a_time.setText(hourOfDay + ":" + minute);
}
}, hour, mint,true);
timePickerDialog.show();
}
});
}
class ShipDetail extends AsyncTask<String, String, String[]> {
HttpURLConnection connection = null;
BufferedReader reader = null;
#Override
protected String[] doInBackground(String... params) {
Log.i(TAG, "URL : " + params[0]);
String result1;
String result2;
String result3;
String result4;
String result5;
String[] resultArray = new String[5];
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
Log.i(TAG, "Connected");
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
Log.i(TAG, "Data Read");
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String json = buffer.toString();
Log.i(TAG, "LINE ## : " + json);
if (json.equals("No Data Found")) {
resultArray[0] = "No Data Found";
} else {
JSONObject shipdetailObject = new JSONObject(json);
JSONObject parentKey = shipdetailObject.getJSONObject("detail");
result1 = parentKey.getString("loa");
result2 = parentKey.getString("beam");
result3 = parentKey.getString("grt");
result4 = parentKey.getString("nrt");
result5 = parentKey.getString("pcno");
resultArray[0] = result1;
resultArray[1] = result2;
resultArray[2] = result3;
resultArray[3] = result4;
resultArray[4] = result5;
return resultArray;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return resultArray;
}
#Override
protected void onPostExecute(String[] s) {
super.onPostExecute(s);
if (s[0].equals("No Data Found")) {
Toast.makeText(AgentActivity.this, "" + s[0], Toast.LENGTH_SHORT).show();
} else {
String str_loa = s[0];
String str_beam = s[1];
String str_nrt = s[2];
String str_grt = s[3];
String str_pcno = s[4];
Log.i(TAG, "Extracted From JSON LOA: " + str_loa);
Log.i(TAG, "Extracted From JSON BEAM: " + str_beam);
Log.i(TAG, "Extracted From JSON GRT: " + str_grt);
Log.i(TAG, "Extracted From JSON NRT: " + str_nrt);
Log.i(TAG, "Extracted From JSON PCNO: " + str_pcno);
txtloa.setText("L.O.A |" + str_loa);
txtbeam.setText("G.R.T |" + str_beam);
txtgrt.setText("N.R.T |" + str_grt);
txtnrt.setText("BEAM |" + str_nrt);
txtpcno.setText("P.C No. |" + str_pcno);
}
}
}
//downloading initial detail
class DownloadInitialInformation extends AsyncTask<String, String, String> {
HttpURLConnection connection = null;
BufferedReader reader = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(AgentActivity.this,
R.style.AppTheme_Dark_Dialog);
// progressDialog.setIndeterminate(true);
progressDialog.setMessage("Downloading...");
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
Log.i(TAG, "URL : " + params[0]);
//Boolean flag= new Boolean(false);
String flag = "";
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
Log.i(TAG, "Connected");
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
Log.i(TAG, "Data Read");
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String json = buffer.toString();
Log.i(TAG, "LINE ## : " + json);
if (json.equals("No Data Found")) {
flag="N";
}
else{
JSONObject parentObject = new JSONObject(json);
JSONArray parentShipArray = parentObject.getJSONArray("Ship");
JSONArray parentTerminalArray = parentObject.getJSONArray("Terminals");
JSONArray parentCommodityArray = parentObject.getJSONArray("Commodity");
int v_len,t_len,c_len;
v_len = parentShipArray.length();
t_len = parentTerminalArray.length();
c_len = parentCommodityArray.length();
arr_shipname = new String[v_len];
arr_terminal = new String[t_len];
arr_commodity = new String[c_len];
Log.i(TAG, "Ship Length : " + v_len);
Log.i(TAG, "T Length : " + t_len);
Log.i(TAG, "C Length : " + c_len);
//getting ships
for (int i = 0; i < v_len; i++) {
JSONObject ship_json = parentShipArray.getJSONObject(i);
arr_shipname[i] = ship_json.getString("v");
Log.i(TAG, "Ship name : " + arr_shipname[i]);
Log.i(TAG, "Vessel name : "+arr_shipname[2]);
}
//getting terminals
for (int i = 0; i < t_len; i++) {
JSONObject terminal_json = parentTerminalArray.getJSONObject(i);
arr_terminal[i] = terminal_json.getString("t");
Log.i(TAG, "Terminal : " + arr_terminal[i]);
}
//getting commodity
for (int i = 0; i < c_len; i++) {
JSONObject commdty_json = parentCommodityArray.getJSONObject(i);
// arr_commodity.add(commdty_json.getString("c"));
arr_commodity[i] = commdty_json.getString("c");
Log.i(TAG, "Commodity : " + arr_commodity[i]);
}
flag = "Y";
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return flag;
}
#Override
protected void onPostExecute(String downloadStat) {
super.onPostExecute(downloadStat);
Log.i(TAG, "download stat : " + downloadStat);
if (downloadStat.equals("Y")) {
//set all textViews and spinner
// Log.i(TAG, "Commodity : " + arr_commodity[1]);
spnr_commodity = (Spinner) findViewById(R.id.spnr_commodity);
commodityAdapter = new ArrayAdapter<String>(AgentActivity.this, android.R.layout.simple_spinner_item,arr_commodity);
commodityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Log.i(TAG, "Commodity : " + arr_commodity);
spnr_commodity.setAdapter(commodityAdapter);
terminalAdapter = new ArrayAdapter<String>(AgentActivity.this, android.R.layout.simple_spinner_item, arr_terminal);
terminalAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnr_terminal.setAdapter(terminalAdapter);
//Log.i(TAG, "Terminal : " + arr_terminal.toString());
lastportAdapter = new ArrayAdapter<String>(AgentActivity.this,android. R.layout.simple_spinner_item, arr_lastport);
lastportAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
spnr_lastport.setAdapter(lastportAdapter);
//Log.i(TAG, "Last Port : " + arr_lastport.toString());
} else {
Toast.makeText(AgentActivity.this, "No Data Found", Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
}
}
} // End of AgentActivity
*LogCat to Check populated array*
11-14 09:44:18.267 19660-19660/com.portqasim.personal.testinglayout I/TERMINAL﹕ (QICT)-1.1
11-14 09:44:18.267 19660-19660/com.portqasim.personal.testinglayout I/TERMINAL﹕ (QICT)-1.2
11-14 09:44:18.267 19660-19660/com.portqasim.personal.testinglayout I/TERMINAL﹕ (QICT)-2.1
11-14 09:44:18.267 19660-19660/com.portqasim.personal.testinglayout I/TERMINAL﹕ (QICT)-2.2
11-14 09:44:18.268 19660-19660/com.portqasim.personal.testinglayout I/TERMINAL﹕ EVTL-13
11-14 09:44:18.268 19660-19660/com.portqasim.personal.testinglayout I/TERMINAL﹕ FAP GT
11-14 09:44:18.268 19660-19660/com.portqasim.personal.testinglayout I/TERMINAL﹕ FOTCO OIL TERMINAL
11-14 09:44:18.268 19660-19660/com.portqasim.personal.testinglayout I/TERMINAL﹕ IOCB
11-14 09:44:18.268 19660-19660/com.portqasim.personal.testinglayout I/TERMINAL﹕ LCT
11-14 09:44:18.269 19660-19660/com.portqasim.personal.testinglayout I/TERMINAL﹕ MW-1
11-14 09:44:18.269 19660-19660/com.portqasim.personal.testinglayout I/TERMINAL﹕ MW-2
11-14 09:44:18.269 19660-19660/com.portqasim.personal.testinglayout I/TERMINAL﹕ MW-3
11-14 09:44:18.269 19660-19660/com.portqasim.personal.testinglayout I/TERMINAL﹕ MW-4
11-14 09:44:18.269 19660-19660/com.portqasim.personal.testinglayout I/TERMINAL﹕ SSGC/LPG
I can't see your spinner in the xml file. But I had similar issue and was fixed when I added entries in my spinner in the xml. I had all my adapter and spinner items all right but wouldn't get displayed in the spinner without adding the entries in the xml file.
try to set the adapter to spinner after getting all values in list, debug your code and make sure your list has data in it before setting adapter to spinners.
The issue resolved successfully by just changing the spinner mode from dialog to dropdown
Previously
android:spinnerMode="dialog"
Now
android:spinnerMode="dropdown"
the previous xml is here
http://pastebin.com/2G9zt8ht
the correct xml is here
http://pastebin.com/yQEbapkg

cant update data in sqlite database

TextView desc,details,responsibility,status,txtdate;
EditText equipment_id;
DBController controller = new DBController(this,null,null,1);
ImageButton btnupdate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_update_equiments);
equipment_id = (EditText)findViewById(R.id.txtequipmentid);
desc = (TextView)findViewById(R.id.txtdescription);
details = (TextView)findViewById(R.id.txtdetails);
status = (TextView)findViewById(R.id.txtstatus);
txtdate = (TextView)findViewById(R.id.txtdate);
responsibility = (TextView)findViewById(R.id.txtresponsibilitycenter);
btnupdate = (ImageButton)findViewById(R.id.btnupdate);
//desc.setVisibility(View.GONE);
//details.setVisibility(View.GONE);
// responsibility.setVisibility(View.GONE);
// btnupdate.setVisibility(View.GONE);
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(c.getTime());
txtdate.setText(formattedDate);
//update data
btnupdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
//String status = "1";
controller = new DBController(getApplicationContext(), null, null ,1);
SQLiteDatabase database = controller.getWritableDatabase();
ContentValues data = new ContentValues();
data.put("description", desc.getText().toString());
data.put("details", details.getText().toString());
data.put("responsibility_center",responsibility.getText().toString());
data.put("status", status.getText().toString());
data.put("date_taken", txtdate.getText().toString());
database.update("tbl_equipments", data, "equipment_id=" + equipment_id.getText().toString(), null);
//database.update("tbl_equipments", data, "equipment_id=" + equipment_id.getText().toString(), null);
Toast.makeText(Search_Equipments.this, "Updated successfully", Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
Toast.makeText(Search_Equipments.this,ex.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
//search equipment
public void searchEquipment(View view){
if (equipment_id.getText().toString().equals("")){
Toast.makeText(Search_Equipments.this,"Please Enter Equipement No.",Toast.LENGTH_LONG).show();
} else {
controller = new DBController(this, null, null , 1);
Equipment equipment = controller.getEquipment(equipment_id.getText().toString());
if (equipment != null){
desc.setText(String.valueOf(equipment.get_description()));
details.setText(String.valueOf(equipment.get_details()));
responsibility.setText(String.valueOf(equipment.get_responsibility()));
desc.setVisibility(View.VISIBLE);
details.setVisibility(View.VISIBLE);
responsibility.setVisibility(View.VISIBLE);
btnupdate.setVisibility(View.VISIBLE);
}else {
Toast.makeText(Search_Equipments.this,"Not Found",Toast.LENGTH_LONG).show();
}
}
}
can someone help my code. if passed the condition that data successfully updated but when i display the updated data from database data has not updated, can someone help me to fix this. . . . . . because i dont where is my error there. see my update code. thanks :)
You forgot to commit the transaction.
database.setTransactionSuccessful();
database.endTransaction();

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?

Check duplicate editText before writing into .csv

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

Categories

Resources