Spinner is not populating with the data recieved from webservice - android

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

Related

How can I rearrange the data from database in a ListView?

everyone. I have an ArrayList of the data and a ListView to showing up the list of the data. Now what I want to do is rearrange the data when I press the button and sort the data in which data has the highest result.
Here is my code:
public class MainActivity extends AppCompatActivity {
private TextView mTextMessage;
String[] dataDetail;
ArrayList<dataDetail> allDetail = new ArrayList<>();
ListView detailList;
final Context context = this;
final int min = 0;
final int max = 10;
final int random = new Random().nextInt((max - min) + 1) + min;
Button reorder = findViewById(R.id.arrangeId);
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
mTextMessage.setText(R.string.title_home);
return true;
case R.id.navigation_dashboard:
mTextMessage.setText(R.string.title_dashboard);
return true;
}
return false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
detailList = findViewById(R.id.dataView);
mTextMessage = (TextView) findViewById(R.id.message);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
new GetData().execute();
}
private class GetData extends AsyncTask<Void, Void, ArrayList<dataDetail>> {
protected ArrayList<dataDetail> doInBackground(Void... voids) {
HttpURLConnection urlConnection;
InputStream in = null;
try {
URL url = new URL("http://10.0.2.2:8080/projectServer/DataDetailDB?getdata=true");
urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
String response = convertStreamToString(in);
System.out.println("Server response = " + response);
try {
JSONArray jsonArray = new JSONArray(response);
dataDetail = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
final String customerName = jsonArray.getJSONObject(i).get("customerName").toString();
final String carName = jsonArray.getJSONObject(i).get("carName").toString();
final String appointmentDate = jsonArray.getJSONObject(i).get("appointmentDate").toString();
final String email = jsonArray.getJSONObject(i).get("email").toString();
final String issueDescribe = jsonArray.getJSONObject(i).get("issueDescribe").toString();
final String timeForJob = jsonArray.getJSONObject(i).get("timeForJob").toString();
final String costForJob = jsonArray.getJSONObject(i).get("costForJob").toString();
final String reliableOnCar = jsonArray.getJSONObject(i).get("reliableOnCar").toString();
final String distanceJob = jsonArray.getJSONObject(i).get("distance").toString();
dataDetail tData = new dataDetail(customerName, carName, appointmentDate, email, issueDescribe, timeForJob, costForJob, reliableOnCar, distanceJob);
allDetail.add(tData);
System.out.println("customername = " + customerName + "carname = " + carName + "appointmentdate = " + appointmentDate +
"email = " + email + "describe = " + issueDescribe + "time = " + timeForJob + "cost = " + costForJob + "reliable = " + reliableOnCar
+ "dis = " + distanceJob);
dataDetail [i] = "Name: " + customerName + "\n" + "Appointment Date: " + appointmentDate;
reorder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
float finalResult = random * Float.parseFloat(timeForJob) + random * Float.parseFloat(reliableOnCar) +
random * Float.parseFloat(distanceJob) + random * Float.parseFloat(costForJob);
System.out.print("Test result " + finalResult + " ");
/* Trying to sort the data here which has the highest finalResult
* will going to the top of the list */
allDetail = new ArrayList<String>(Arrays.asList(dataDetail));
Collections.sort(allDetail);
ArrayAdapter newList = new ArrayAdapter(context, android.R.layout.simple_list_item_1, dataDetail);
newList.setAdapter(theList);
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(ArrayList<dataDetail> dataDetailArrayList) {
super.onPostExecute(dataDetailArrayList);
ArrayAdapter theList = new ArrayAdapter(context, android.R.layout.simple_list_item_1, dataDetail);
detailList.setAdapter(theList);
}
}
public String convertStreamToString(InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
}
But when I try to use sort I get the error says it's incompatible types.
allDetail = new ArrayList<String>(Arrays.asList(dataDetail));
Collections.sort(allDetail);
The finalResult will do the calculation and get the final result for every data it retrieves from the database. And now I just want to reorder it automatically, This is the logcat:
Please anyone can help how can I do the rearrange for the listview?
Collections.sort() will work. Its your problem related to how your are storing your data in list

my table is full in class and empty in other

I'am a beginner in android and i use AndroidStudio
I have a problem
in have 2 class i my project in the first class "fetch compte" i fill my table "dataParsed" and i 'am certain that the table is fil
but in the second class MainActivity
I find that the table is empty
please help me
this is my code
public class fetchcompte extends AsyncTask<Void,Void,Void> {
String data = "";
String dat = "";
public static String[] dataParsed ;
String singleParsed ;
String dataParse = "";
String singleParse1 = "";
String singleParse2 = "";
String singleParse3 = "";
String singleParse4 = "";
String singleParse5 = "";
private RequestQueue mQueue, mQueu;
int nbcompte;
protected Void doInBackground(Void... voids) {
String S = jsonArray;
// singleParsed=new String[20];
dataParsed=new String[20];
try {
// String url2="http://recrutement.stb.com.tn:1010/PlateformeApi_Externe/api/ComptesClient/000001498675\n";
//String url2 = "http://10.1.11.168:8081/my/banks/10/accounts/10403082500589678844/transactions";
String url2 = "http://10.12.0.66:8081/api/ComptesClient/000001498675";
URL url = new URL(url2);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while (line != null) {
line = bufferedReader.readLine();
data = data + line;
}
JSONArray JA = new JSONArray(data);
nbcompte=JA.length();
for(int i =0 ;i<nbcompte; i++) {
JSONObject JO = (JSONObject) JA.get(i);
singleParsed = "fullname:" + JO.get("fullname");
singleParse1 = "accountnumber:" + JO.get("accountnumber");
singleParse2 = "rib:" + JO.get("rib");
singleParse3 = "iban:" + JO.get("iban");
singleParse4 = "name:" + JO.get("name");
singleParse5 = "balance:" + JO.get("balance");
dataParsed[i] = singleParsed + "\n" + singleParse1 + "\n" + singleParse2 + "\n" + singleParse3 + "\n" + singleParse4 + "\n" + singleParse5;
}
// dataParsed[i] =dataParsed[i] +singleParsed[i] +"\n" ;
// MainActivity.compte[i]=dataParsed[i];
// singleParsed[i] = "fullname:" + JO.get("fullname") + "\n"+
// "accountnumber:" + JO.get("accountnumber") + "\n"+
// "rib:" + JO.get("rib") + "\n"+
// "iban:" + JO.get("iban") + "\n"+
// "name:" + JO.get("name") + "\n"+
//"balance:" + JO.get("balance") + "\n";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
for(int i =0 ;i <2; i++) {
// MainActivity.data.setText(this.d[i]);
}
}
//Authorization Bearer
my MainActivity
import static com.example.saiid.listecompte.fetchcompte.dataParsed;
public class MainActivity extends AppCompatActivity {
Button click;
public static TextView data;
public static String jsonArray;
private RequestQueue mQueue;
ImageView imageView2;
public static TextView textView_type;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mQueue = Volley.newRequestQueue(this);
click = (Button) findViewById(R.id.button_parse);
data = (TextView) findViewById(R.id.text_view_result);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setContentView(R.layout.listeview);
CustomAdaptercompte customAdapter=new CustomAdaptercompte();
ListView listeview=(ListView) findViewById(R.id.liste);
listeview.setAdapter(customAdapter);
fetchcompte process = new fetchcompte();
process.execute();
}
});
}
public class CustomAdaptercompte extends BaseAdapter {
#Override
public int getCount() {
return 2;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View convertView, ViewGroup viewgrp) {
View view = getLayoutInflater().inflate(R.layout.customlayout,null);
imageView2 = (ImageView) view.findViewById(R.id.imageView2);
textView_type =(TextView) view.findViewById(R.id.textView_type);
imageView2.setImageResource(R.drawable.compte);
textView_type.setText(dataParsed[i]);
return view;
}
}
}
The mistake that you have made is that you assume that
import static com.example.saiid.listecompte.fetchcompte.dataParsed;
will automatically just be the dataParsed Variable you need. What that line does is that it gets the default value of dataParsed (from a default fetchcompte instance). Since you make another instance of a fetchcompte object [called process] (which you are using to populate its dataParsed variable) simply access the dataParsed variable of that instance.
So instead of using:
textView_type.setText(dataParsed[i]);
You can use:
textView_type.setText(process.dataParsed[i]);
But to do this you will need to somehow access the process variable in your adapter class.

How to update the Recylerview View items after displayed First Json URL In android

I having a problem update the Item in Recycler View.I will explain clearly about my problem.
I am using two Json URL's first Json URL can send the items to model class.
after completed this called the adapter, then update the second Json URL items with the adapter by using setter model class.
so that's why called adapter.notifyitemchanged, but only one time can updated items next time while looping doesn't update the items display empty for second time.
Code:
public void servicecallsingle(String list, final int pin) {
url = Constants.singleproducturl + list;
JsonObjectRequest request1 = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener < JSONObject > () {
#Override
public void onResponse(JSONObject response) {
JSONObject response1 = response;
if (response1 != null) {
// int status=jsonObject.optInt("status");
String status = response1.optString("status");
if (status.equalsIgnoreCase("200")) { //check the status 200 or not
try {
productpath = response1.getString("productPath");
} catch (JSONException e) {
e.printStackTrace();
}
try {
JSONObject responses = response1.getJSONObject("response");
jsonarray = responses.getJSONArray(DATA);
if (jsonarray.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < jsonarray.length(); i++) {
item = new CartItemoriginal();
JSONObject product = jsonarray.getJSONObject(i);
cartpid = product.getString("product_id");
cartproductname = product.getString("product_name");
cartaliasname = product.getString("product_alias");
cartprice = product.getString("mrp_price");
String sp = product.getString("selling_price");
String op = product.getString("offer_selling_price");
sellerid = product.getString("seller_id");
JSONArray pimg = product.getJSONArray("product_images");
JSONObject firstimg = pimg.getJSONObject(0);
cartimg = firstimg.getString("original_res");
String[] img2 = cartimg.split("\\.");
String imagone = productpath + sellerid + '/' + img2[0] + '(' + '2' + '0' + '0' + ')' + '.' + img2[1];
String Quantity = product.getString("product_max_add");
String minqty = product.getString("product_min_add");
int qty = Integer.parseInt(Quantity);
/*** calculation ***/
Long tsLong = System.currentTimeMillis() / 1000;
String ts = tsLong.toString();
int ts1 = Integer.parseInt(ts);
String startdate1 = product.getString("offer_selling_start_date");
String endate1 = product.getString("offer_selling_end_date");
if (("".equals(startdate1)) && ("".equals(endate1))) {
// Toast.makeText(getActivity(),"wrong statemnt",Toast.LENGTH_LONG).show();
if (cartprice.equalsIgnoreCase(sp)) {
double d = Double.parseDouble(cartprice);
int mrp = (int) d;
price = String.valueOf(mrp);
} else {
double s = Double.parseDouble(sp);
int sales = (int) s;
price = String.valueOf(sales);
}
} else {
int startdate = Integer.parseInt(startdate1);
int endate2 = Integer.parseInt(endate1);
if (ts1 > startdate && ts1 < endate2) {
double offer = Double.parseDouble(op);
int offers = (int) offer;
price = String.valueOf(offers);
} else {
if (cartprice.equalsIgnoreCase(sp)) {
double d = Double.parseDouble(cartprice);
int mrp = (int) d;
price = String.valueOf(mrp);
} else {
double s = Double.parseDouble(sp);
int sales = (int) s;
price = String.valueOf(sales);
}
}
}
item.setProductname(cartproductname);
item.setQty(1);
item.setProductimg(imagone);
item.setMaxquantity(Quantity);
item.setAliasname(cartaliasname);
item.setPrice(price);
item.setMinquantity(minqty);
item.setProductid(cartpid);
cart.add(item);
// cart.add(new CartItemoriginal(imagone,cartproductname,cartaliasname,1,Quantity,minqty,price,cartpid));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} // condtion check the status 200
else // this is if status falied in runtime
{
Toast.makeText(CartItems.this, "Status Failed in Banner Page check ur network connection", Toast.LENGTH_LONG).show();
}
// llm = new LinearLayoutManager(CartItems.this);
MainLinear.setVisibility(View.VISIBLE);
final CustomLinearLayoutManagercartpage layoutManager = new CustomLinearLayoutManagercartpage(CartItems.this, LinearLayoutManager.VERTICAL, false);
recyleitems.setHasFixedSize(false);
recyleitems.setLayoutManager(layoutManager);
cartadapter = new CartlistAdapter(cart, CartItems.this);
Log.i(String.valueOf(cartadapter), "cartadapter");
recyleitems.setAdapter(cartadapter);
recyleitems.setNestedScrollingEnabled(false);
myView.setVisibility(View.GONE);
cartadapter.notifyDataSetChanged();
}
String id = cartpid;
String selleid = sellerid;
final int pinnum = pin;
String pinurl = "http://192.168.0.33/sharpswebsite3/qcrest1.0/?type=pinCodeCheck&result=json&product_id=" + id + "&seller_id=" + selleid + "&pinCode=" + pinnum;
JsonObjectRequest request2 = new JsonObjectRequest(Request.Method.GET, pinurl, null, new Response.Listener < JSONObject > () {
#Override
public void onResponse(JSONObject responsesecond) {
JSONObject response2 = responsesecond;
// do something with response1 & response here...
if (response2 != null) {
// int status=jsonObject.optInt("status");
String status = response2.optString("status");
if (status.equalsIgnoreCase("200")) { //check the status 200 or not
try {
JSONObject responses = response2.getJSONObject("response");
jsonarray = responses.getJSONArray(DATA);
if (jsonarray.length() > 0) {
Log.i(String.valueOf(jsonarray.length()), "message");
// looping through json and adding to movies list
for (int j = 0; j < jsonarray.length(); j++) {
JSONObject product = jsonarray.getJSONObject(j);
process = product.getString("process");
Message = product.getString("message");
if (process.equalsIgnoreCase("success") && Message.equalsIgnoreCase("success")) {
cartdelivery = product.getString("delivery");
cartshippingcharge = product.getString("shipping_charge");
String pincode = product.getString("pincode");
/**************************calculation of shipping days**************************/
int day = Integer.parseInt(cartdelivery);
Calendar c = Calendar.getInstance();
String dayNumberSuffix = getDayNumberSuffix(day);
SimpleDateFormat sdf = new SimpleDateFormat(" MMM d'" + dayNumberSuffix + "', yyyy");
String currentDateandTime = sdf.format(new Date());
try {
c.setTime(sdf.parse(currentDateandTime));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.DATE, day);
Date resultdate = new Date(c.getTimeInMillis());
currentDateandTime = sdf.format(resultdate);
Log.d(String.valueOf(currentDateandTime), "shipping days");
cart.get(j).setDelivery("Standard delivery by" + " " + currentDateandTime);
cart.get(j).setShippincharge(cartshippingcharge);
cart.get(j).setSellername("richard feloboune");
cartadapter.notifyItemChanged(j);
cartadapter.notifyItemRangeChanged(j, cart.size());
} else {
// cart2.add(new Cartitemoringinaltwo("Seller doesn't deliver to this item to"+" "+ String.valueOf(pinnum)));
cart.get(j).setError("Seller doesn't deliver to this item to" + " " + String.valueOf(pinnum));
cartadapter.notifyItemChanged(j);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
// stopping swipe refresh
// swipeRefreshLayout.setRefreshing(false);
} // condtion check the status 200
else // this is if status falied in runtime
{
Toast.makeText(CartItems.this, "Status Failed in Banner Page check ur network connection", Toast.LENGTH_LONG).show();
}
}
pincheck();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("onErrorResponse", error.toString());
}
});
AppController.getInstance().addToRequestQueue(request2);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("onErrorResponse", error.toString());
}
});
AppController.getInstance().addToRequestQueue(request1);
}
Note: While looping first time can set the item in setter model class but second couldn't set the item to model class.
Anyone solve this problem glad to appreciate.
Thanks in advance
The problem is volley doesn't wait for the request to be completed. So as the first call is made within seconds other call will be also made. So, you need to create an interface which will be called when the first webservice is called, and than in interface call other webservice and than notifyDataSet.
public void servicecallsingle(String list, final int pin) {
url = Constants.singleproducturl + list;
JsonObjectRequest request1 = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener < JSONObject > () {
#Override
public void onResponse(JSONObject response) {
JSONObject response1 = response;
if (response1 != null) {
// int status=jsonObject.optInt("status");
String status = response1.optString("status");
if (status.equalsIgnoreCase("200")) { //check the status 200 or not
try {
productpath = response1.getString("productPath");
} catch (JSONException e) {
e.printStackTrace();
}
parseJson(response1, new WebServiceCallBack{
public void getWebserviceCallBack(){
// Call another webservice here
String id = cartpid;
String selleid = sellerid;
final int pinnum = pin;
String pinurl = "http://192.168.0.33/sharpswebsite3/qcrest1.0/?type=pinCodeCheck&result=json&product_id=" + id + "&seller_id=" + selleid + "&pinCode=" + pinnum;
JsonObjectRequest request2 = new JsonObjectRequest(Request.Method.GET, pinurl, null, new Response.Listener < JSONObject > () {
#Override
public void onResponse(JSONObject responsesecond) {
JSONObject response2 = responsesecond;
// do something with response1 & response here...
if (response2 != null) {
// int status=jsonObject.optInt("status");
String status = response2.optString("status");
if (status.equalsIgnoreCase("200")) { //check the status 200 or not
try {
JSONObject responses = response2.getJSONObject("response");
jsonarray = responses.getJSONArray(DATA);
if (jsonarray.length() > 0) {
Log.i(String.valueOf(jsonarray.length()), "message");
// looping through json and adding to movies list
for (int j = 0; j < jsonarray.length(); j++) {
JSONObject product = jsonarray.getJSONObject(j);
process = product.getString("process");
Message = product.getString("message");
if (process.equalsIgnoreCase("success") && Message.equalsIgnoreCase("success")) {
cartdelivery = product.getString("delivery");
cartshippingcharge = product.getString("shipping_charge");
String pincode = product.getString("pincode");
/**************************calculation of shipping days**************************/
int day = Integer.parseInt(cartdelivery);
Calendar c = Calendar.getInstance();
String dayNumberSuffix = getDayNumberSuffix(day);
SimpleDateFormat sdf = new SimpleDateFormat(" MMM d'" + dayNumberSuffix + "', yyyy");
String currentDateandTime = sdf.format(new Date());
try {
c.setTime(sdf.parse(currentDateandTime));
} catch (ParseException e) {
e.printStackTrace();
}
c.add(Calendar.DATE, day);
Date resultdate = new Date(c.getTimeInMillis());
currentDateandTime = sdf.format(resultdate);
Log.d(String.valueOf(currentDateandTime), "shipping days");
cart.get(j).setDelivery("Standard delivery by" + " " + currentDateandTime);
cart.get(j).setShippincharge(cartshippingcharge);
cart.get(j).setSellername("richard feloboune");
cartadapter.notifyItemChanged(j);
cartadapter.notifyItemRangeChanged(j, cart.size());
} else {
// cart2.add(new Cartitemoringinaltwo("Seller doesn't deliver to this item to"+" "+ String.valueOf(pinnum)));
cart.get(j).setError("Seller doesn't deliver to this item to" + " " + String.valueOf(pinnum));
cartadapter.notifyItemChanged(j);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
// stopping swipe refresh
// swipeRefreshLayout.setRefreshing(false);
} // condtion check the status 200
else // this is if status falied in runtime
{
Toast.makeText(CartItems.this, "Status Failed in Banner Page check ur network connection", Toast.LENGTH_LONG).show();
}
}
pincheck();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("onErrorResponse", error.toString());
}
});
AppController.getInstance().addToRequestQueue(request2);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("onErrorResponse", error.toString());
}
});
AppController.getInstance().addToRequestQueue(request1);
});
}
} // condtion check the status 200
else // this is if status falied in runtime
{
Toast.makeText(CartItems.this, "Status Failed in Banner Page check ur network connection", Toast.LENGTH_LONG).show();
}
// llm = new LinearLayoutManager(CartItems.this);
MainLinear.setVisibility(View.VISIBLE);
final CustomLinearLayoutManagercartpage layoutManager = new CustomLinearLayoutManagercartpage(CartItems.this, LinearLayoutManager.VERTICAL, false);
recyleitems.setHasFixedSize(false);
recyleitems.setLayoutManager(layoutManager);
cartadapter = new CartlistAdapter(cart, CartItems.this);
Log.i(String.valueOf(cartadapter), "cartadapter");
recyleitems.setAdapter(cartadapter);
recyleitems.setNestedScrollingEnabled(false);
myView.setVisibility(View.GONE);
cartadapter.notifyDataSetChanged();
}
public void parseJson(JSONObject response1, WebServiceCallBack webserviceCallBack){
try {
JSONObject responses = response1.getJSONObject("response");
jsonarray = responses.getJSONArray(DATA);
if (jsonarray.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < jsonarray.length(); i++) {
item = new CartItemoriginal();
JSONObject product = jsonarray.getJSONObject(i);
cartpid = product.getString("product_id");
cartproductname = product.getString("product_name");
cartaliasname = product.getString("product_alias");
cartprice = product.getString("mrp_price");
String sp = product.getString("selling_price");
String op = product.getString("offer_selling_price");
sellerid = product.getString("seller_id");
JSONArray pimg = product.getJSONArray("product_images");
JSONObject firstimg = pimg.getJSONObject(0);
cartimg = firstimg.getString("original_res");
String[] img2 = cartimg.split("\\.");
String imagone = productpath + sellerid + '/' + img2[0] + '(' + '2' + '0' + '0' + ')' + '.' + img2[1];
String Quantity = product.getString("product_max_add");
String minqty = product.getString("product_min_add");
int qty = Integer.parseInt(Quantity);
/*** calculation ***/
Long tsLong = System.currentTimeMillis() / 1000;
String ts = tsLong.toString();
int ts1 = Integer.parseInt(ts);
String startdate1 = product.getString("offer_selling_start_date");
String endate1 = product.getString("offer_selling_end_date");
if (("".equals(startdate1)) && ("".equals(endate1))) {
// Toast.makeText(getActivity(),"wrong statemnt",Toast.LENGTH_LONG).show();
if (cartprice.equalsIgnoreCase(sp)) {
double d = Double.parseDouble(cartprice);
int mrp = (int) d;
price = String.valueOf(mrp);
} else {
double s = Double.parseDouble(sp);
int sales = (int) s;
price = String.valueOf(sales);
}
} else {
int startdate = Integer.parseInt(startdate1);
int endate2 = Integer.parseInt(endate1);
if (ts1 > startdate && ts1 < endate2) {
double offer = Double.parseDouble(op);
int offers = (int) offer;
price = String.valueOf(offers);
} else {
if (cartprice.equalsIgnoreCase(sp)) {
double d = Double.parseDouble(cartprice);
int mrp = (int) d;
price = String.valueOf(mrp);
} else {
double s = Double.parseDouble(sp);
int sales = (int) s;
price = String.valueOf(sales);
}
}
}
item.setProductname(cartproductname);
item.setQty(1);
item.setProductimg(imagone);
item.setMaxquantity(Quantity);
item.setAliasname(cartaliasname);
item.setPrice(price);
item.setMinquantity(minqty);
item.setProductid(cartpid);
cart.add(item);
// cart.add(new CartItemoriginal(imagone,cartproductname,cartaliasname,1,Quantity,minqty,price,cartpid));
}
}
} catch (JSONException e) {
e.printStackTrace();}
webserviceCallBack.getWebserviceCallBack();
}
public interface WebServiceCallBack{
public void getWebserviceCallBack()
}

how do i apply a condition when the fields are empty then it never post the data to the mysql data base

I am trying to post data to mysql data base and it post it. But now i am trying to apply check if the fields in activity are empty - and data isn't posted to database.
public class Accepter extends Activity implements OnClickListener{
private EditText etName,etAge,etCity,etContact,etQuantity;
private Spinner spBloodGroup;
private ImageView imCancel,imSave;
private String message = "POST";
private static String[] BLOOD_GROUPS = {"Select Blood Group","A +Ve","B +Ve","AB +Ve","O +Ve","A -Ve","B -Ve","AB -Ve","O -Ve"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.accepter_entry_form);
etName = (EditText)findViewById(R.id.etNameAcc);
etAge = (EditText)findViewById(R.id.etAgeAcc);
etCity = (EditText)findViewById(R.id.etCityAcc);
etContact = (EditText)findViewById(R.id.etPhoneNoAcc);
etQuantity = (EditText)findViewById(R.id.etQuantityAcc);
spBloodGroup = (Spinner)findViewById(R.id.spBloodGroupAcc);
imCancel = (ImageView)findViewById(R.id.imCancelAcc);
imSave = (ImageView)findViewById(R.id.imSaveAcc);
imCancel.setOnClickListener(this);
imSave.setOnClickListener(this);
ArrayAdapter<String> bgAdapter = new ArrayAdapter<String>(Accepter.this,android.R.layout.simple_spinner_item,BLOOD_GROUPS);
bgAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spBloodGroup.setAdapter(bgAdapter);
}
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.imSaveAcc:
String name = etName.getText().toString();
String blood = spBloodGroup.getSelectedItem().toString();
String quantity = etQuantity.getText().toString();
String phone = etContact.getText().toString();
int age = Integer.parseInt(etAge.getText().toString());
String city = etCity.getText().toString();
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month= c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
String date = String.valueOf(day) + "-" + String.valueOf(month) + "-" + String.valueOf(year);
if(name.length()>1 && blood.length()>1 && phone.length()>1 && age>15 && city.length()>1)
{
AccepterTask task = new AccepterTask(v.getContext());
task.execute(message ,name, blood, phone, String.valueOf(age),city,quantity,date);
etName.setText("");
spBloodGroup.setSelection(0);
etContact.setText("");
etAge.setText("");
etCity.setText("");
etQuantity.setText("");
finish();
}
else
{
Toast.makeText(Accepter.this, "Any field is empty or invalid", Toast.LENGTH_LONG).show();
}
break;
case R.id.imCancelAcc:
Intent i = new Intent(v.getContext(),MainView.class);
i.putExtra("type", "Accepter");
startActivity(i);
break;
}
}
public class AccepterTask extends AsyncTask<String, Void, String>{
private Context context;
private JSONParser jsonParser = new JSONParser();
private JSONObject json;
private String accepter_url = //"http://192.168.0.6/accepter.php";
"http://10.0.2.2/accepter.php";
private String s;
public AccepterTask(Context c)
{
context = c;
}
#Override
protected String doInBackground(String... params)
{
String message = params[0];
if(message.equals("POST"))
{
List<NameValuePair> list = new ArrayList<NameValuePair>();
final String names = params[1];
final String blood = params[2];
final String phone = params[3];
final String age = params[4];
final String city = params[5];
final String quantity = params[6];
final String date = params[7];
list.add(new BasicNameValuePair("name", names));
list.add(new BasicNameValuePair("blood", blood));
list.add(new BasicNameValuePair("quantity", quantity));
list.add(new BasicNameValuePair("phone", phone));
list.add(new BasicNameValuePair("age", age));
list.add(new BasicNameValuePair("city", city));
list.add(new BasicNameValuePair("date", date));
json = jsonParser.makeHttpRequest(accepter_url, params[0], list);
}
try
{
s = json.getString("message");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return s;
}
#Override
protected void onPostExecute(String result)
{
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
}
}
here for updates

How to retrieve RSS FEED from Yahoo weather

I've tried to retrieve RSS data from Yahho weather ,however my code couldn't work.
May I know what's wrong with it?
The Url that I've use is http://weather.yahooapis.com/forecastrss?w=1062617&u=c.
I'm a newbie in programming, Kindly seek your advice to it.
Thanks
the below are my coding.
CXActivity.java
public class CXActivity extends Activity {
/** Called when the activity is first created. */
ListView listview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RestClient rc = new RestClient();
//the account key might not work. Please insert your own set.
ArrayList<Weather> list1 = rc.getPlaces("", "");
int index = 3;
String[] listArray = new String[list1.size()];
StringBuilder sb = new StringBuilder();
int counter = 0;
for(int i = 1; i<list1.size(); i++)
{
sb.append("\n\nEntry #: " + i);
sb.append("\n" + "Title: \""+ list1.get(i).getTitle() + "\"");
sb.append("\n" + "Publish Date: \""+ list1.get(i).getPubDate() +"\"");
sb.append("\n" + "Condition: \""+ list1.get(i).getCondition()+"\"");
sb.append("\n" + "Forecast: \""+ list1.get(i).getForecast()+"\"");
listArray[counter] = sb.toString();
counter++;
sb.delete(0, sb.capacity());
}
listview=(ListView)findViewById(R.id.ListView01);
listview.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , listArray));
}
}
RestClient.java
public class RestClient
{
ArrayList weatherList;
//This is the function responsible to pull data from web service.
public ArrayList<Weather> getPlaces(String accountKey, String uniqueId)
{
weatherList = new ArrayList<Weather>();
try {
URL _url = new URL("http://weather.yahooapis.com/forecastrss?w=1062617&u=c");
URLConnection _urlConn = _url.openConnection();
_urlConn.addRequestProperty("AccountKey", accountKey);
_urlConn.addRequestProperty("UniqueUserID", uniqueId);
BufferedReader br = new BufferedReader(new InputStreamReader(_urlConn.getInputStream()));
String line = null;
StringBuilder strBuilder = new StringBuilder();
while ((line = br.readLine()) != null) {
strBuilder.append(line);
System.out.println(line);
}
String[] IProperties = strBuilder.toString().split("<m:properties>");
for (String str : IProperties)
{
Weather weather = new Weather();
weather.setTitle(Utils.getStringBetween(str, "<title>", "</<title>>"));
weather.setPubDate(Utils.getStringBetween(str, "<pubDate>", "</pubDate>"));
weather.setCondition(Utils.getStringBetween(str, "<yweather:condition>", "</yweather:condition>"));
weather.setForecast(Utils.getStringBetween(str, "<yweather:forecast>", "</yweather:forecast>"));
weatherList.add(weather);
}
}
catch (MalformedURLException ex)
{
ex.printStackTrace();
}
catch (IOException ex)
{
ex.printStackTrace();
}
catch (Exception ex)
{
ex.printStackTrace();
}
return weatherList;
}
//This is a helper function to get specific traffic data structure
public Weather getPlacesAtIndex(ArrayList<Weather> list, int index)
{
if(list.size() <= index) return null;
return list.get(index);
}
}
Utils.java
public class Utils {
//This functions get the xml data between the xml elements
public static String getStringBetween(String src, String start, String end)
{
StringBuilder sb = new StringBuilder();
int startIdx = src.indexOf(start) + start.length();
int endIdx = src.indexOf(end);
while(startIdx < endIdx)
{
sb.append("" + String.valueOf(src.charAt(startIdx)));
startIdx++;
}
return sb.toString();
}
}
weather.java
public class Weather {
String Title;
String PubDate;
String Condition;
String Forecast;
public String getTitle() {
return Title;
}
public void setTitle(String title) {
Title = title;
}
public String getPubDate() {
return PubDate;
}
public void setPubDate(String pubDate) {
PubDate = pubDate;
}
public String getCondition() {
return Condition;
}
public void setCondition(String condition) {
Condition = condition;
}
public String getForecast() {
return Forecast;
}
public void setForecast(String forecast) {
Forecast = forecast;
}
}
Please change your activity code.
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
ListView listview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RestClient rc = new RestClient();
// the account key might not work. Please insert your own set.
ArrayList<Weather> list1 = rc.getPlaces("", "");
int index = 3;
String[] listArray = new String[list1.size()];
StringBuilder sb = new StringBuilder();
int counter = 0;
Log.e("N", "listArray::" + list1.size());
for (int i = 0; i < list1.size(); i++) {
sb.append("\n\nEntry #: " + i);
sb.append("\n" + "Title: \"" + list1.get(i).getTitle() + "\"");
sb.append("\n" + "Publish Date: \"" + list1.get(i).getPubDate()
+ "\"");
sb.append("\n" + "Condition: \"" + list1.get(i).getCondition()
+ "\"");
sb.append("\n" + "Forecast: \"" + list1.get(i).getForecast() + "\"");
listArray[counter] = sb.toString();
counter++;
sb.delete(0, sb.capacity());
}
Log.e("N", "listArray::" + listArray.length);
listview = (ListView) findViewById(R.id.listView);
listview.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listArray));
}
}

Categories

Resources