Android empty listview with poor internet connection - android

I have a listview being populated with data from the server. If I use wifi connection everything works fine.
Is there anything that I could do to improve this code to wait until the data is full loaded from the server with bad connections like 3G or poor wifi connection?
Sometimes listview gets empty.
public class LoadAsync extends AsyncTask<String, Boolean, Boolean>{
public ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ListEvents.this);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(String... params) {
// Creating volley request obj
JsonArrayRequest eventReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
pDialog.dismiss();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Event event = new Event();
event.setImovel_id(obj.getString("imovel_id"));
event.setThumbnailUrl(obj.getString("arquivo"));
event.setNegocio(obj.getString("negocio"));
event.setImovel(obj.getString("imovel"));
event.setMobilia(obj.getString("mobilia"));
event.setGaragem(obj.getString("garagem"));
event.setPreco(obj.getString("preco"));
city = obj.getString("city").trim();
statee = obj.getString("state").trim();
checkNegocio = obj.getString("negocio").trim();
checkImovel = obj.getString("imovel").trim();
checkMobilia = obj.getString("mobilia").trim();
checkGaragem = obj.getString("garagem").trim();
checkPreco = obj.getString("preco").trim();
checkPreco = checkPreco.replace("R", "");
checkPreco = checkPreco.replaceAll("[$.,]", "");
int serverprice = Integer.parseInt(checkPreco);
String app_price = checkP.getText().toString();
app_price = app_price.replace("R", "");
app_price = app_price.replaceAll("[$.,]", "");
int i_price = Integer.parseInt(app_price);
if(estado.getText().toString().trim().equalsIgnoreCase(statee) &&
cidade.getText().toString().trim().equalsIgnoreCase(city) &&
checkN.getText().toString().trim().equalsIgnoreCase(checkNegocio)){
if(/*checkI.getText().toString().equalsIgnoreCase(checkImovel) ||
checkM.getText().toString().equalsIgnoreCase(checkMobilia) ||
checkG.getText().toString().equalsIgnoreCase(checkGaragem) ||*/
serverprice <= i_price){
// adding event to events array
eventList.add(event);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} if(eventList.size() > 0){
listView.setAdapter(adapter);
listView.setTextFilterEnabled(true);
}else{
noEvent.setText("Nothing found.");
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.dismiss();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(eventReq);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String imovelID = ((TextView) view.findViewById(R.id.imovel_id)).getText().toString();
ImageView eFile = ((ImageView) view.findViewById(R.id.thumbnail));
String imgUrl = (String) eFile.getTag();
String negocio = ((TextView) view.findViewById(R.id.negocio)).getText().toString();
String imovel = ((TextView) view.findViewById(R.id.imovel)).getText().toString();
String mobilia = ((TextView) view.findViewById(R.id.mobilia)).getText().toString();
String garagem = ((TextView) view.findViewById(R.id.garagem)).getText().toString();
String preco = ((TextView) view.findViewById(R.id.preco)).getText().toString();
Intent i = new Intent(getApplicationContext(), EventDetails.class);
i.putExtra(TAG_ID, imovelID);
i.putExtra(TAG_ARQUIVO, imgUrl);
i.putExtra(TAG_NEGOCIO, negocio);
i.putExtra(TAG_IMOVEL, imovel);
i.putExtra(TAG_MOBILIA, mobilia);
i.putExtra(TAG_GARAGEM, garagem);
i.putExtra(TAG_PRECO, preco);
startActivity(i);
}
});
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
//pDialog.dismiss();
}
}

Show an indeterminate ProgressBar, till your data is loaded. Cancel the progress bar once the loading is complete
Refer:
http://developer.android.com/reference/android/widget/ProgressBar.html
Also see Android indeterminate progress bar

Related

Get listview data while checked and pass it to another activity

Ive been searching for the right answer but nothing can solve my problems. I have a list view which is populated by my database from webserver. So basically what need is to get the data from the listview that is checked by user and pass the data to another activity. Sorry for my bad english hope you guys can help me.
Error ive received
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
at java.util.ArrayList.get(ArrayList.java:304)
at firin.myuploads.Attendance$1.onClick(Attendance.java:74)
Attendance.java
public class Attendance extends AppCompatActivity {
//For Checkbox
ArrayList<String> selectedItems=new ArrayList<>();
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
private CheckBox cb;
private Button bGet;
//private id[] id;
private static String url = "www.myphpurl.com";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance);
contactList = new ArrayList<>();
bGet = (Button) findViewById(R.id.button7);
lv = (ListView) findViewById(R.id.list);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
new GetContacts().execute();
bGet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// String selected =((TextView)view.findViewById(R.id.mobile)).getText().toString();
CheckBox cb = (CheckBox) findViewById(R.id.cb);
cb.setChecked(true);
int len = lv.getCount();
SparseBooleanArray checked = lv.getCheckedItemPositions();
for (int i = 0; i < len; i++)
if (checked.get(i)) {
String item = selectedItems.get(i);
Toast.makeText(getApplicationContext(), item, Toast.LENGTH_LONG).show();
/*some code to save data in MainActivity*/
Intent in = new Intent(Attendance.this, SendMail.class);
in.putExtra("ListValue", item);
startActivity(in);}
}
});
}
This is the code where i populate my data to the listview
public class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray result = jsonObj.getJSONArray("result");
// looping through All Contacts
for (int i = 0; i < result.length(); i++) {
JSONObject c = result.getJSONObject(i);
String id = c.getString("userID");
String studentName = c.getString("studentName");
String parentName = c.getString("parentName");
String parentEmail = c.getString("parentEmail");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("UID", id);
contact.put("sName", studentName);
contact.put("pName", parentName);
contact.put("pEmail", parentEmail);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Attendance.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
public void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Attendance.this, contactList,
R.layout.list_item, new String[]{"sName", "pName",
"pEmail"}, new int[]{R.id.name,
R.id.email, R.id.mobile});
lv.setAdapter(adapter);
}
}
Is this how i set my setOnClick?
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String selected =((TextView)findViewById(R.id.mobile)).getText().toString();
CheckBox cb = (CheckBox) findViewById(R.id.cb);
cb.setChecked(true);
}});
Hope you guys can help me. thanks in advance
First you need to get how many item is selected in the listview, then after store in another array and pass that array to another activity.
Set you listview selection mode as Multi Choice.
listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Set Listener on listview as below
ArrayList<String> selectedItem = new ArrayList();
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setSelected(true);
adapter.getView(position, view, parent).setBackgroundColor(getResources().getColor(R.color.btn_login));
adapter.notifyDataSetChanged();
Log.i(TAG, "Selected Item is " + stateList.get(position));
selectedItem.add(yourArray.get(position))
}
});
you can invok your intent and pass selectedItem to that intent like this
Intent intent = new Intent(activity, YourActivity.class);
intent.putStringArrayListExtra("selected_list", selectedItem);
startActivity(intent);
and In your receiving intent you need to do:
ArrayList<String> selectedItem;
Intent i = getIntent();
selectedItem = i.getStringArrayListExtra("selected_list");

Get specific json object from listview click

I have my class that is based on a tutorial online, i dont fully understand it yet ( working on it ), but its working.
It populates the listview, now i want to get the id and show the data related to that id on a more detailed activity.
I already obtain the id of the item i am clicking:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
Log.e("item clicks", "selected: " + position);
}
});
But now, i am not getting how i will do this, get the data of the position i clicked.
I have a inner class "GetObras" but i cant use the variables from it on my onCreate, i tried make them global, etc
public class MainActivity extends ActionBarActivity implements SearchView.OnQueryTextListener{
private String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private ListView list;
private static String url = "http://ploran.gear.host/scriptobras6.php";
ArrayList<HashMap<String, String>> obrasList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
obrasList = new ArrayList<HashMap<String, String>>();
list = (ListView)findViewById(R.id.list1);
new GetObras().execute();
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
Log.e("item clicks", "selected: " + position);
}
});
}
private class GetObras extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
//JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray obras = new JSONArray(jsonStr);
// Getting JSON Array node
//JSONArray obras = jsonObj.getJSONArray("obras");
// looping through All
for (int i = 0; i < obras.length(); i++) {
JSONObject c = obras.getJSONObject(i);
String id = c.getString("Id");
String nomeObra = c.getString("NomeObra");
String idCliente = c.getString("idCliente");
String DataLevantamento = c.getString("DataPLevantamento");
String DataRealizacao = c.getString("DataRLevantamento");
String Estado = c.getString("Estado");
String DataMateriais = c.getString("DataRMateriais");
String DataInicioObra = c.getString("DataInicioObra");
String DataConclusao = c.getString("DataConclusao");
String DataVestoria = c.getString("DataVestoria");
String Obs = c.getString("Obs");
String Prompor = c.getString("Prompor");
String Levantpor = c.getString("Levantpor");
String executpor = c.getString("executpor");
// tmp hash map for single contact
HashMap<String, String> obra = new HashMap<>();
// adding each child node to HashMap key => value
obra.put("Id", id);
obra.put("nomeObra", nomeObra);
obra.put("idCliente", idCliente);
obra.put("DataLevantamento", DataLevantamento);
obra.put("DataRealizacao", DataRealizacao);
obra.put("Estado", Estado);
obra.put("DataMateriais", DataMateriais);
obra.put("DataIncioObra", DataInicioObra);
obra.put("DataConclusao", DataConclusao);
obra.put("DataVestoria", DataVestoria);
obra.put("Obs", Obs);
obra.put("Prompor", Prompor);
obra.put("Levantpor", Levantpor);
obra.put("executpor", executpor);
// adding contact to contact list
obrasList.add(obra);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, obrasList,
R.layout.list_item, new String[]{"nomeObra", "idCliente",
"Estado"}, new int[]{R.id.name,
R.id.email, R.id.mobile});
list.setAdapter(adapter);
}
}
List<String> cities;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_search, menu);
MenuItem searchItem = menu.findItem(R.id.search);
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
// User pressed the search button
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// User changed the text
return false;
}
}
If what i think is correct, i could just get the JsonArray from the doInBackground method in GetObras and do:
JSONObject c = obras.getJSONObject(position);
Thank you.
You can retrieve it using obrasList reference. As your are passing obrasList to your adapter.
Below is the sample code:
obrasList.get(position).get(yourkey);
Hope this will help you.. :))

Transaction ID set correctly, but displayed only a submit later

My code gives correct response and sets transaction ID correctly. But on screen, the ID is missing the first time I submit, and when I go back and submit again, then the ID on screen is the ID of the first transaction.
On the first submit, this is rendered:
MOBILE NUMBER: 9129992929
OPERATOR: AIRTEL
AMOUNT: 344
TRANSACTION ID:
On the second submit, this is rendered:
MOBILE NUMBER: 9129992929
OPERATOR: AIRTEL
AMOUNT: 344
TRANSACTION ID: NUFEC37WD537K5K2P9WX
I want to see the second screen the first time I submit.
Response to the first submit:
D/TID IS: ====>NUFEC37WD537K5K2P9WX D/UID IS:
====>27W3NDW71XRUR83S7RN3 D/Response-------: ------>{"tid":"NUFEC37WD537K5K2P9WX","uid":"27W3NDW71XRUR83S7RN3","status":"ok"}
Response to the second submit:
D/TID IS: ====>18R6YXM82345655ZL3E2 D/UID IS:
====>27W3NDW71XRUR83S7RN3 D/Response-------: ------>{"tid":"18R6YXM82345655ZL3E2","uid":"27W3NDW71XRUR83S7RN3","status":"ok"}
The code generating the response:
public class Prepaid extends Fragment implements View.OnClickListener {
Button submit_recharge;
Activity context;
RadioGroup _RadioGroup;
public EditText number, amount;
JSONObject jsonobject;
JSONArray jsonarray;
ArrayList<String> datalist, oprList;
ArrayList<Json_Data> json_data;
TextView output, output1;
String loginURL = "http://www.www.example.com/operator_details.php";
ArrayList<String> listItems = new ArrayList<>();
ArrayAdapter<String> adapter;
String data = "";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootview = inflater.inflate(R.layout.prepaid, container, false);
submit_recharge = (Button) rootview.findViewById(R.id.prepaid_submit);
number = (EditText) rootview.findViewById(R.id.prenumber);
amount = (EditText) rootview.findViewById(R.id.rechergpre);
submit_recharge.setOnClickListener(this);
context = getActivity();
new DownloadJSON().execute();
return rootview;
}
public void onClick(View v) {
MyApplication myRecharge = (MyApplication) getActivity().getApplicationContext();
final String prepaid_Number = number.getText().toString();
String number_set = myRecharge.setNumber(prepaid_Number);
final String pre_Amount = amount.getText().toString();
String amount_set = myRecharge.setAmount(pre_Amount);
Log.d("amount", "is" + amount_set);
Log.d("number", "is" + number_set);
switch (v.getId()) {
case R.id.prepaid_submit:
if (prepaid_Number.equalsIgnoreCase("") || pre_Amount.equalsIgnoreCase("")) {
number.setError("Enter the number please");
amount.setError("Enter amount please");
} else {
int net_amount_pre = Integer.parseInt(amount.getText().toString().trim());
String ph_number_pre = number.getText().toString();
if (ph_number_pre.length() != 10) {
number.setError("Please Enter valid the number");
} else {
if (net_amount_pre < 10 || net_amount_pre > 2000) {
amount.setError("Amount valid 10 to 2000");
} else {
AsyncTaskPost runner = new AsyncTaskPost(); // for running AsyncTaskPost class
runner.execute();
Intent intent = new Intent(getActivity(), Confirm_Payment.class);
startActivity(intent);
}
}
}
}
}
}
/*
*
* http://pastie.org/10618261
*
*/
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
MyApplication myOpt = (MyApplication) getActivity().getApplicationContext();
protected Void doInBackground(Void... params) {
json_data = new ArrayList<Json_Data>();
datalist = new ArrayList<String>();
// made a new array to store operator ID
oprList = new ArrayList<String>();
jsonobject = JSONfunctions
.getJSONfromURL(http://www.www.example.com/operator_details.php");
Log.d("Response: ", "> " + jsonobject);
try {
jsonarray = jsonobject.getJSONArray("data");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
Json_Data opt_code = new Json_Data();
opt_code.setName(jsonobject.optString("name"));
opt_code.setId(jsonobject.optString("ID"));
json_data.add(opt_code);
datalist.add(jsonobject.optString("name"));
oprList.add(jsonobject.getString("ID"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void args) {
final Spinner mySpinner = (Spinner) getView().findViewById(R.id.operator_spinner);
mySpinner
.setAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item,
datalist));
mySpinner
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
String opt_code = oprList.get(position);
String selectedItem = arg0.getItemAtPosition(position).toString();
Log.d("Selected operator is==", "======>" + selectedItem);
Log.d("Selected Value is======", "========>" + position);
Log.d("Selected ID is======", "========>" + opt_code);
if (opt_code == "8" || opt_code == "14" || opt_code == "35" || opt_code == "36" || opt_code == "41" || opt_code == "43") // new code
{
_RadioGroup = (RadioGroup) getView().findViewById(R.id.radioGroup);
_RadioGroup.setVisibility(View.VISIBLE);
int selectedId = _RadioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
final RadioButton _RadioSex = (RadioButton) getView().findViewById(selectedId);
_RadioSex.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (null != _RadioSex && isChecked == false) {
Toast.makeText(getActivity(), _RadioSex.getText(), Toast.LENGTH_LONG).show();
}
Toast.makeText(getActivity(), "Checked In button", Toast.LENGTH_LONG).show();
Log.d("Checked In Button", "===>" + isChecked);
}
});
}
String user1 = myOpt.setOperator(opt_code);
String opt_name = myOpt.setOpt_provider(selectedItem);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
private class AsyncTaskPost extends AsyncTask<String, Void, Void> {
MyApplication mytid = (MyApplication)getActivity().getApplicationContext();
String prepaid_Number = number.getText().toString();
String pre_Amount = amount.getText().toString();
protected Void doInBackground(String... params) {
String url = "http://www.example.com/android-initiate-recharge.php";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
public void onResponse(String response) {
try {
JSONObject json_Response = new JSONObject(response);
String _TID = json_Response.getString("tid");
String _uid = json_Response.getString("uid");
String _status = json_Response.getString("status");
String tid_m =mytid.setTransaction(_TID);
Log.d("TID IS","====>"+tid_m);
Log.d("UID IS", "====>" + _uid);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Response-------", "------>" + response);
}
},
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
Log.e("Responce error==","===>"+error);
error.printStackTrace();
}
}
) {
MyApplication uid = (MyApplication) getActivity().getApplicationContext();
final String user = uid.getuser();
MyApplication operator = (MyApplication) getActivity().getApplicationContext();
final String optcode = operator.getOperator();
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
// the POST parameters:
params.put("preNumber", prepaid_Number);
params.put("preAmount", pre_Amount);
params.put("key", "XXXXXXXXXX");
params.put("whattodo", "prepaidmobile");
params.put("userid", user);
params.put("category", optcode);
Log.d("Value is ----------", ">" + params);
return params;
}
};
Volley.newRequestQueue(getActivity()).add(postRequest);
return null;
}
protected void onPostExecute(Void args) {
}
}
class Application
private String _TId;
public String getTId_name() {
return _TId;
}
public String setTId_name(String myt_ID) {
this._TId = myt_ID;
Log.d("Application set TID", "====>" + myt_ID);
return myt_ID;
}
class Confirm_pay
This is where the ID is set.
MyApplication _Rechargedetail =(MyApplication)getApplicationContext();
confirm_tId =(TextView)findViewById(R.id._Tid);
String _tid =_Rechargedetail.getTId_name();
confirm_tId.setText(_tid);
Because you have used Volley library which is already asynchronous, you don't have to use AsyncTask anymore.
Your code can be updated as the following (not inside AsyncTask, direct inside onCreate for example), pay attention to // update TextViews here...:
...
String url = "http://www.example.com/index.php";
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject json_Response = new JSONObject(response);
String _TID = json_Response.getString("tid");
String _uid = json_Response.getString("uid");
String _status = json_Response.getString("status");
String tid_m =mytid.setTId_name(_TID);
Log.d("TID IS","====>"+tid_m);
Log.d("UID IS","====>"+_uid);
// update TextViews here...
txtTransId.setText(_TID);
txtStatus.setText(_status);
...
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Response-------", "------>" + response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Responce error==","===>"+error);
error.printStackTrace();
}
}
requestQueue.add(postRequest);
...
P/S: since the reponse data is a JSONObject, so I suggest you use JsonObjectRequest instead of StringRequest. You can read more at Google's documentation.
Hope it helps!
Your line of code should be executed after complete execution of network operation and control comes in onPostExecute(); of your AsyncTask.
confirm_tId.setText(_tid);

How to implement a proper scroll in list view to implement pagination on fragment activity?

I am building an application like techcrunch. I am fetching data from server in JSON format and displaying the data in list view like article title,author name and image. I have applied pagination means when user scroll more articles load in a list view. My pagination works fine but there is an issue in the scroll function as the fresh or new data loads the scroll dose not aligns with the data. To clarify more in simple words my scroll-er goes at the top of the page when i am actually scrolling down this is my code :
public class OneFragment extends Fragment {
public OneFragment(){}
private static final String TAG = OneFragment.class.getSimpleName();
// Movies json url
private static String URL = "http:url&page=1";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
int current_page = 1;
int mPreLast;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.swip, container, false);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.show();
pDialog.setCancelable(false);
listView = (ListView) rootView.findViewById(R.id.list49);
listView.setOnScrollListener(new AbsListView.OnScrollListener()
{
#Override
public void onScrollStateChanged(AbsListView absListView, int i)
{
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
{
int lastItem = firstVisibleItem + visibleItemCount;
if(lastItem == totalItemCount){
if (mPreLast != lastItem)
{
mPreLast = lastItem;
onStart();
}
}
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int Position,
long offset) {
// TODO Auto-generated method stub
Movie item = (Movie) adapter.getItem(Position);
Intent intent = new Intent(rootView.getContext(), SingleArticle.class);
single.date = item.getDate();
single.id = item.getId();
startActivity(intent);
}
});
//pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
return rootView;
}
#Override
public void onStart(){
super.onStart();
// calling adapter changes here, just
// to avoid getactivity()null
// increment current page
current_page += 1;
// Next page request
URL = "http:url&page=" + current_page;
//adapter = new CustomListAdapter(this, movieList);
// changing action bar color
//getActivity().getActionBar().setBackground(
//new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setDate(obj.getString("date"));
movie.setId(obj.getString("id"));
movieList.add(movie);
int currentPosition = listView.getFirstVisiblePosition();
adapter = new CustomListAdapter(getActivity(), movieList);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
listView.setSelectionFromTop(currentPosition + 1, 0);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
new AlertDialog.Builder(getActivity())
.setTitle("No Connectivity ")
.setMessage("Please check your internet connectivity!")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
//.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
//public void onClick(DialogInterface dialog, int which) {
// do nothing
//}
//})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(movieReq);
listView.setAdapter(adapter);
}
private View getActionBar() {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
You can try this (I added a line to set the new list position in the last line of onStart())
With this line you can set the new position_
listView.setSelectionFromTop(newPosition, 0);
With the first parameter you set the position, and with the second you set the distnace from the top of the list
#Override
public void onStart(){
super.onStart();
// calling adapter changes here, just
// to avoid getactivity()null
// increment current page
current_page += 1;
// Next page request
URL = "http:url&page=" + current_page;
//adapter = new CustomListAdapter(this, movieList);
// changing action bar color
//getActivity().getActionBar().setBackground(
//new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest movieReq = new JsonArrayRequest(URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Movie movie = new Movie();
movie.setDate(obj.getString("date"));
movie.setId(obj.getString("id"));
movieList.add(movie);
int currentPosition = listView.getFirstVisiblePosition();
adapter = new CustomListAdapter(getActivity(), movieList);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
listView.setSelectionFromTop(currentPosition + 1, 0);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
new AlertDialog.Builder(getActivity())
.setTitle("No Connectivity ")
.setMessage("Please check your internet connectivity!")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
//.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
//public void onClick(DialogInterface dialog, int which) {
// do nothing
//}
//})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(movieReq);
listView.setAdapter(adapter);
//Set the new position
listView.setSelectionFromTop(currentPosition + 1, 0);
}

Only the original thread that created a view hierarchy can touch its views android

I'm having a this error Only the original thread that created a view hierarchy can touch its views.
But i don't know how to handle the ui in multithread, like list view and i don't know where to put it.
// Download JSON in Background
public class DownloadJSONFileAsync extends AsyncTask<String, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
}
#Override
protected Void doInBackground(String... params) {
deviceId = generateDeviceId();
elementsList.add(new BasicNameValuePair("DeviceID", deviceId));
JSONObject json = jsonParser.makeHttpRequest(
url_get_reports, "POST", elementsList);
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS_REPORT);
// successfully created
// getting JSON string from URL
try {
if (success == 1) {
reports = json.getJSONArray(TAG_Report);
report_data = new Report[reports.length()];
// looping through All Products
for (int i = reports.length()-1; i >= 0; i--) {
JSONObject c = reports.getJSONObject(i);
reportID = c.getString("reportID");
Drawable drawable = LoadImageFromWeb(url+c.getString(TAG_IMAGE));
String state = "";
if(c.getString("state").equals("1")){
state = "Pinding";
}else if(c.getString("state").equals("2")){
state = "Inprogress";
}else{
state = "Completed";
}
if(c.getString(TAG_TITLE).equals("")){
report_data[i] = new Report(reportID,"Report "+(i+1),c.getString(TAG_TIME),drawable,url+c.getString(TAG_IMAGE),state,c.getString("coordination")) ;
}else{
report_data[i] = new Report(reportID,c.getString(TAG_TITLE),c.getString(TAG_TIME),drawable,url+c.getString(TAG_IMAGE),state,c.getString("coordination"));
}
if(json.getInt("successReplies")==1){
replies = json.getJSONArray(TAG_REPLIES);
ArrayList<String> arr = new ArrayList<String>();
for(int j=0;j<replies.length();j++){
JSONObject c2 = replies.getJSONObject(j);
if(reportID.equals(c2.getString("ReportID")))
{
arr.add(c2.getString("RepliesContent")+"\n"+c2.getString("RepliesTime"));
}
}
report_data[i].setRepliesArray(arr);
}
}
list = (ListView)findViewById(R.id.list);
ReportAdapter adapter = new ReportAdapter(Display_Reports.this,report_data);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(
AdapterView<?> arg0, View arg1,
int position, long id) {
Intent intent = new Intent(Display_Reports.this, Display_Report_Details.class);
intent.putExtra("ID", report_data[position].ID);
intent.putExtra("Name", report_data[position].Name);
intent.putExtra("State", report_data[position].State);
intent.putExtra("Time", report_data[position].Time);
intent.putExtra("ImageUrl", report_data[position].ImageUrl);
intent.putExtra("Coordination", report_data[position].Coordination);
intent.putStringArrayListExtra("RepliesContent", report_data[position].getRepliesArray());
startActivity(intent);
}
});
} else {
// no Entities found
Toast.makeText(Display_Reports.this, "No reports found",
Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void unused) {
dismissDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
removeDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
}
}
You cannot modify the UI from a background thread. Whether you use AsyncTask, or a Handler, or runOnUiThread(), or post(), to have work done on the main application thread is up to you.
You may wish to review the documentation on threads and some of these techniques.

Categories

Resources