I am facing a weird issue in my app. It is working perfectly in Android Kitkat Version but in Lollipop devices I am having a weird issue. Issue is that there is a fragment named help List and currently it is having no records therefore I just show a toast there that No Records found. But after this screen is opened when I open any other fragment in my app they all show no data at all, whether it is static or dynamic. Here are the screen shots to explain it more clearly
This is the original view of this screen
And after opening that fragment that is without data, It looks like this,
More over when I press the home button and then navigate back to app everything is visible again.
Here is the code for this fragment
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp">
<com.bluejamesbond.text.DocumentView
xmlns:ext="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ext:documentView_text="Doorstep Help is the most dynamic on demand service and helper application which shall make your life simple and easy. Get a servant at your door starting from Re 1/- per minute. Looking for someone to help you in shifting your house? Get a Moving Service Doorstep Helper starting at Re 3/- per minute. Want a servant for household chores like deep-cleaning, grocery buying? Get a Doorstep Household servant at your door for instant help. Need a helping hand to wash all your clothes? Get a Doorstep Laundry Helper to wash all your clothes. Your one stop solution for on-demand service and Help!"
ext:documentView_textSize="18sp"
ext:documentView_textAlignment="justified"/>
</LinearLayout>
And java file just have onCreateView and nothing else so I don't think that's necessary.
And this blank thing happens with every screen after that.
I have no clue what's causing this
I am also adding code for Help List fragment. It consists of two tabs
public class FragmentHelpList extends Fragment {
private ViewPager viewPager;
Context context;
public FragmentHelpList(){}
//#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my_help_list, container, false);
PagerSlidingTabStrip tabsStrip = (PagerSlidingTabStrip) rootView.findViewById(R.id.tabs);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
viewPager.setAdapter(new TabFragmentPagerAdapter(getActivity().getSupportFragmentManager()));
// Attach the view pager to the tab strip
tabsStrip.setViewPager(viewPager);
return rootView;
}
And these are the two fragments added to view pager
First One
public static SlidingTab1Fragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
SlidingTab1Fragment fragment = new SlidingTab1Fragment();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
appSharedPreferences= AppSharedPreferences.getsharedprefInstance(getActivity()) ;
userid = appSharedPreferences.getUserId();
System.out.println("allhelpstabid : " + userid);
ALLHELPS_URL = Baseurl + "job_working.php?customer_id="+appSharedPreferences.getUserId();
new Loadalljobs().execute();
return inflater.inflate(R.layout.tab1, container, false);
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
}
public void updatedisplay(ArrayList<HashMap<String, String>> container) {
TabOneCustomAdapter myCustomAdapter = new TabOneCustomAdapter(getActivity().getBaseContext(), R.layout.tab1_singleitem, container);
setListAdapter(myCustomAdapter);
myCustomAdapter.notifyDataSetChanged();
Log.d("display execution", "");
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3) {
// String value = (String) adapter.getItemAtPosition(position);
HashMap<String, String> map = AllHelpsList.get(position);
Intent i = new Intent(getActivity(), ActivityHelpDetailsCurrent.class);
i.putExtra("name", map.get(TAG_NAME));
i.putExtra("address", map.get(TAG_ADDRESS));
i.putExtra("date", map.get(TAG_DATE));
startActivity(i);
}
});
}
class Loadalljobs extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading All Helps ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
ClearListAdapter clearadapter = new ClearListAdapter();
clearadapter.clearData();
setListAdapter(clearadapter);
}
#Override
protected String doInBackground(Void... params) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(ALLHELPS_URL, ServiceHandler.GET);
System.out.println("Response:" + jsonStr);
Log.d("All Helps JSON: ", "> " + jsonStr);
AllHelpsList.clear();
return jsonStr;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject=new JSONObject(s);
int status=jsonObject.getInt("status");
if (status==1) {
JSONArray jsonArray=jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
String name = c.getString(TAG_NAME);
String address = c.getString(TAG_ADDRESS);
String date = c.getString(TAG_DATE);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_NAME, name);
map.put(TAG_ADDRESS, address);
map.put(TAG_DATE, date);
Log.d("kirti error", map + "");
AllHelpsList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
updatedisplay(AllHelpsList);
// dismiss the dialog after getting all products
if (pDialog.isShowing())
pDialog.dismiss();
islListViewLoaded = false;
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
System.out.println("Item clicked");
Intent i = new Intent(getActivity(), ActivityHelpDetailsCurrent.class);
startActivity(i);
super.onListItemClick(l, v, position, id);
}
#Override
public void onStop() {
super.onStop();
if(pDialog!= null)
pDialog.dismiss();
}
And the second fragment
public static SlidingTab2Fragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
SlidingTab2Fragment fragment = new SlidingTab2Fragment();
fragment.setArguments(args);
return fragment;
}
// Inflate the fragment layout we defined above for this fragment
// Set the associated text for the title
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
appSharedPreferences= AppSharedPreferences.getsharedprefInstance(getActivity()) ;
prefs = this.getActivity().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
userid = appSharedPreferences.getUserId();
System.out.println("SCHEDULED_helpstabid : " + userid);
SCHEDULED_URL=Baseurl+"job_scheduled.php?cid="+userid;
System.out.println("Second tab url is: " +SCHEDULED_URL);
new LoadScheduled().execute();
return inflater.inflate(R.layout.tab2, container, false);
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
}
public void updatedisplay(ArrayList<HashMap<String, String>> container) {
TabTwoCustomAdapter myCustomAdapter = new TabTwoCustomAdapter(getActivity().getBaseContext(), R.layout.tab2_singleitem, container);
setListAdapter(myCustomAdapter);
Log.d("display execution", "");
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3) {
// String value = (String) adapter.getItemAtPosition(position);
HashMap<String, String> map = ScheduledHelpsList.get(position);
Intent i = new Intent(getActivity(), ActivityHelpDetailsScheduled.class);
i.putExtra("name", map.get(TAG_NAME));
i.putExtra("address", map.get(TAG_ADDRESS));
i.putExtra("time", map.get(TAG_TIME));
i.putExtra("date",map.get(TAG_DATE));
startActivity(i);
}
});
}
/**
* Background Async Task to Load all OUTBOX messages by making HTTP Request
*/
class LoadScheduled extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading Scheduled Helps ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
ClearListAdapter clearadapter = new ClearListAdapter();
clearadapter.clearData();
setListAdapter(clearadapter);
}
/**
* getting Outbox JSON
*/
protected String doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(SCHEDULED_URL, ServiceHandler.GET);
Log.d("Scheduled JSON: ", "> " + jsonStr);
System.out.println("Response:" + jsonStr);
ScheduledHelpsList.clear();
try {
JSONArray ja = new JSONArray(jsonStr);
for (int i = 0; i < ja.length(); i++) {
JSONObject c = ja.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_NAME);
String address = c.getString(TAG_ADDRESS);
String time = c.getString(TAG_TIME);
String jobtime = c.getString(TAG_DURATION);
String job_amount = c.getString(TAG_AMOUNT);
String date = c.getString(TAG_DATE);
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NAME, name);
map.put(TAG_ADDRESS, address);
map.put(TAG_TIME, time);
map.put(TAG_DURATION, jobtime);
map.put(TAG_AMOUNT, job_amount);
map.put(TAG_DATE, date);
// adding HashList to ArrayList
ScheduledHelpsList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
updatedisplay(ScheduledHelpsList);
if (pDialog.isShowing())
pDialog.dismiss();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
appSharedPreferences= AppSharedPreferences.getsharedprefInstance(getActivity()) ;
userid = appSharedPreferences.getUserId();
System.out.println("allhelpstabid : " + userid);
ALLHELPS_URL = Baseurl + "job_working.php?customer_id="+appSharedPreferences.getUserId();
new Loadalljobs().execute();
return inflater.inflate(R.layout.tab1, container, false);
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
}
public void updatedisplay(ArrayList<HashMap<String, String>> container) {
TabOneCustomAdapter myCustomAdapter = new TabOneCustomAdapter(getActivity().getBaseContext(), R.layout.tab1_singleitem, container);
setListAdapter(myCustomAdapter);
myCustomAdapter.notifyDataSetChanged();
Log.d("display execution", "");
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3) {
// String value = (String) adapter.getItemAtPosition(position);
HashMap<String, String> map = AllHelpsList.get(position);
Intent i = new Intent(getActivity(), ActivityHelpDetailsCurrent.class);
i.putExtra("name", map.get(TAG_NAME));
i.putExtra("address", map.get(TAG_ADDRESS));
i.putExtra("date", map.get(TAG_DATE));
startActivity(i);
}
});
}
class Loadalljobs extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading All Helps ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
ClearListAdapter clearadapter = new ClearListAdapter();
clearadapter.clearData();
setListAdapter(clearadapter);
}
#Override
protected String doInBackground(Void... params) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(ALLHELPS_URL, ServiceHandler.GET);
System.out.println("Response:" + jsonStr);
Log.d("All Helps JSON: ", "> " + jsonStr);
AllHelpsList.clear();
return jsonStr;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject=new JSONObject(s);
int status=jsonObject.getInt("status");
if (status==1) {
JSONArray jsonArray=jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
String name = c.getString(TAG_NAME);
String address = c.getString(TAG_ADDRESS);
String date = c.getString(TAG_DATE);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_NAME, name);
map.put(TAG_ADDRESS, address);
map.put(TAG_DATE, date);
Log.d("kirti error", map + "");
AllHelpsList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
updatedisplay(AllHelpsList);
// dismiss the dialog after getting all products
if (pDialog.isShowing())
pDialog.dismiss();
islListViewLoaded = false;
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
System.out.println("Item clicked");
Intent i = new Intent(getActivity(), ActivityHelpDetailsCurrent.class);
startActivity(i);
super.onListItemClick(l, v, position, id);
}
#Override
public void onStop() {
super.onStop();
if(pDialog!= null)
pDialog.dismiss();
}
And this the adapter class for view pager
public class TabFragmentPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 2;
private String tabTitles[] = new String[] { "Current", "Scheduled"};
public TabFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
Fragment fragment=null;
switch (position) {
case 0:
return SlidingTab1Fragment.newInstance(0);
case 1:
return SlidingTab2Fragment.newInstance(0);
default:
return fragment;
}
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
}
Related
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.. :))
After switching to sdk24, I have a problem.
read json php application, but no longer updated. You must give closure forces her to reread.
before I used to refresh and update listfragment perfect. not now.
I give I add new information is added to the database, or you can delete, but the application does not update.
code json reader + inserd + deleted + refresh:
public class playlist_torrent extends ListFragment {
Main2Activity activity= (Main2Activity) getActivity();
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://vrt.ro/remote/index-torrent.php?token=";
// JSON Node names
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_IMAGE = "image";
private static final String TAG_ADDRESS = "address";
String POPUP_LOGIN_TITLE;
String POPUP_LOGIN_TEXT;
String EMAIL_HINT;
String PASSWORD_HINT;
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_playlist_torrent, container, false);
POPUP_LOGIN_TITLE=getActivity().getString(R.string.text_titlu_insert_stream_playlist);
POPUP_LOGIN_TEXT=getActivity().getString(R.string.text_completeaza_datele);
EMAIL_HINT=getActivity().getString(R.string.name_torrent);
PASSWORD_HINT=getActivity().getString(R.string.magnet_torrent);
final FloatingActionButton actionA = (FloatingActionButton) v.findViewById(R.id.action_a);
actionA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
actionA.setTitle(getActivity().getString(R.string.text_add_new_url));
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setTitle(POPUP_LOGIN_TITLE);
alert.setMessage(POPUP_LOGIN_TEXT);
// Set an EditText view to get user input
final EditText name = new EditText(getActivity());
name.setHint(EMAIL_HINT);
final EditText url_streaming = new EditText(getActivity());
url_streaming.setHint(PASSWORD_HINT);
LinearLayout layout = new LinearLayout(getActivity().getApplicationContext());
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(name);
layout.addView(url_streaming);
alert.setView(layout);
alert.setPositiveButton(getActivity().getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if (url_streaming.getText().toString().compareToIgnoreCase("") == 0) {
Snackbar.make(view, R.string.error_url_emty_playlist, Snackbar.LENGTH_LONG).show();
return;
}
new Thread() {
public void run() {
try {
HttpURLConnection.setFollowRedirects(false);
// note : you may also need
//HttpURLConnection.setInstanceFollowRedirects(false)
Bundle args = getArguments();
String token = args.getString("token");
String name_streaming = name.getText().toString();
String Url_streaming = url_streaming.getText().toString();
HttpURLConnection con = (HttpURLConnection) new URL("http://vrt.ro/remote/insert-torrent.php?token="+token+"&nume="+name_streaming+"&url="+Url_streaming).openConnection();
con.setRequestMethod("HEAD");
if(con.getResponseCode() == HttpURLConnection.HTTP_OK) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(playlist_torrent.this).attach(playlist_torrent.this).commit();
// Reload current fragment
}
else{
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
});
alert.setNegativeButton(getActivity().getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
});
final FloatingActionButton actionB = (FloatingActionButton) v.findViewById(R.id.action_b);
actionB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
actionB.setTitle(getActivity().getString(R.string.refresh_done));
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(playlist_torrent.this).attach(playlist_torrent.this).commit();
}
});
return v;
}
#Override
public void onViewCreated (View view, Bundle savedInstanceState) {
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
// getting values from selected ListItem
final String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
final String id_stream = ((TextView) view.findViewById(R.id.id_streaming)).getText().toString();
// Starting single contact activity
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AppCompatAlertDialogStyle);
builder.setTitle("Select");
// builder.setMessage("Lorem ipsum dolor ....");
builder.setItems(new CharSequence[]
{getString(R.string.play_video), getString(R.string.remove_video)},
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which) {
case 0:
TorrentPlayerFragment fragment3 = new TorrentPlayerFragment();
fragment3.onDestroyView();
FragmentTransaction fragmentTransaction3 = getFragmentManager().beginTransaction();
Bundle args = new Bundle();
args.putString("url", description);
fragment3.setArguments(args);
fragmentTransaction3.addToBackStack(null);
//getFragmentManager().popBackStack();
fragmentTransaction3.remove(fragment3);
fragmentTransaction3.replace(R.id.frame,fragment3);
fragmentTransaction3.commit();
//----
break;
case 1:
// Snack Bar
Snackbar bar = Snackbar.make(view, R.string.confirm_delete_playlist, Snackbar.LENGTH_LONG)
.setAction(R.string.yes, new View.OnClickListener() {
#Override
public void onClick(View v) {
// ---Control remote api---
new Thread() {
public void run() {
try {
HttpURLConnection.setFollowRedirects(false);
// note : you may also need
//HttpURLConnection.setInstanceFollowRedirects(false)
HttpURLConnection con = (HttpURLConnection) new URL("http://vrt.ro/remote/delete-torrent.php?id="+id_stream).openConnection();
con.setRequestMethod("HEAD");
if(con.getResponseCode() == HttpURLConnection.HTTP_OK) {
//--refresh fragment
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(playlist_torrent.this).attach(playlist_torrent.this).commit();
//Fin refresh fragment
// startActivity(getIntent());
// finish();
/* final Handler handler = new Handler();
Runnable refresh = new Runnable() {
#Override
public void run() {
new onPreExecute().execute();
handler.postDelayed(this, 60 * 1000);
}
};
handler.postDelayed(refresh, 60 * 1000); */
}
else{
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}.start();
// ----fin Control remote api----
}
});
bar.show();
break;
}
}
});
builder.create().show();
}
});
// Calling async task to get json
new GetContacts().execute();
}
public static void createDirectory(File dir) throws IllegalStateException{
if (!dir.exists()){
if(!dir.mkdirs()){
throw new IllegalStateException(
"Check if you've added permissions in AndroidManifest.xml: \n" +
"<uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\"/> \n"
);
}
}
}
/**
* Async task class to get json by making HTTP call
*
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Bundle bundle = getActivity().getIntent().getExtras();
//String token = bundle.getString("id");
Bundle args = getArguments();
String myString = args.getString("token");
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url+myString, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray(myString);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String image = c.getString(TAG_IMAGE);
String address = c.getString(TAG_ADDRESS);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_NAME, name);
contact.put(TAG_IMAGE, image);
contact.put(TAG_ADDRESS, address);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
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(
getActivity(), contactList,
R.layout.list_item, new String[]{TAG_NAME, TAG_ID,
TAG_ADDRESS}, new int[]{R.id.name, R.id.id_streaming, R.id.mobile});
setListAdapter(adapter);
}
}
}
This is the code from refresh:
//--refresh fragment
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(playlist_torrent.this).attach(playlist_torrent.this).commit();
//Fin refresh fragment
please help. thank you.
Edit:
if you leave an interval of a few minutes and refresh it goes. but only one time. as if the connection remains open and no longer responds.
Fixed this problem from changed ngix from apache2 and now is work fine.
I have been having a problem lately, I have successfully created a listview in the FillList method that displays the items that i need. That is all well. The problem is how do I convert it to a multi-select checkbox like style so that when I select an item it will just be stored in an array for later use. Any insight is helpful.
Here is my PathfinderUpdate.java:
public class PathfinderUpdate extends Fragment {
ConnectionClass connectionClass;
EditText edtproname, edtprodesc;
Button btnadd,btnupdate,btndelete,btnrefresh;
ProgressBar pbbar;
ListView lstpro;
String pathid;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.update_pathfinder, container, false);
connectionClass = new ConnectionClass();
btnupdate = (Button) rootView.findViewById(R.id.btnupdate);
lstpro = (ListView) rootView.findViewById(R.id.lstproducts);
btnrefresh = (Button) rootView.findViewById(R.id.btnrefresh);
pathid = "";
FillList fillList = new FillList();
fillList.execute("");
btnrefresh.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
FillList Fill = new FillList();
Fill.execute("");
}
});
return rootView;
}
#Override
public void onResume(){
super.onResume();
FillList Fill = new FillList();
Fill.execute("");
}
public class FillList extends AsyncTask<String, String, String> {
String z = "";
List<Map<String, String>> prolist = new ArrayList<Map<String, String>>();
#Override
protected void onPreExecute() {
//old pbbar
}
#Override
protected void onPostExecute(String r) {
String[] from = { "pathfinder_id", "pathfinder_name"};
int[] views = { R.id.lblproid, R.id.lblproname };
final SimpleAdapter ADA = new SimpleAdapter(getActivity(),
prolist, R.layout.lsttemplate, from,views);
lstpro.setAdapter(ADA);
lstpro.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
#SuppressWarnings("unchecked")
HashMap<String, Object> obj = (HashMap<String, Object>) ADA
.getItem(arg2);
pathid = (String) obj.get("pathfinder_id");
String idea_name = (String) obj.get("pathfinder_name");
String benefit_eqv = (String) obj.get("pathfinder_eqv");
String quickwin = (String) obj.get("pathfinder_quick");
String observe = (String) obj.get("pathfinder_obs");
String ideaId = (String) obj.get("pathfinder_idea_id");
String BenefitId = (String) obj.get("pathfinder_benefit");
String closure = (String) obj.get("pathfinder_closure");
Integer ideaIdMain = Integer.parseInt(ideaId);
Integer benefitIdMain = Integer.parseInt(BenefitId);
Integer pathfinderId = Integer.parseInt(pathid);
Double benefiteqv = Double.parseDouble(benefit_eqv);
Bundle bundle = new Bundle();
bundle.putString("id2", pathid);
bundle.putString("name", idea_name);
bundle.putDouble("eqv", benefiteqv);
bundle.putString("quick", quickwin);
bundle.putString("observation", observe);
bundle.putInt("idea_id", ideaIdMain);
bundle.putInt("benefit_id", benefitIdMain);
bundle.putString("closure", closure);
bundle.putInt("id", pathfinderId);
Intent updateMain = new Intent(getActivity(), PathfinderUpdateMain.class);
updateMain.putExtras(bundle);
startActivity(updateMain);
// qty.setText(qtys);
}
});
}
#Override
protected String doInBackground(String... params) {
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
String query = "select * from pathfinder ORDER BY pathfinder_id ASC";
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
ArrayList<String> data1 = new ArrayList<String>();
while (rs.next()) {
Map<String, String> datanum = new HashMap<String, String>();
datanum.put("pathfinder_id", rs.getString("pathfinder_id"));
datanum.put("pathfinder_name", rs.getString("pathfinder_name"));
datanum.put("pathfinder_status", rs.getString("pathfinder_status"));
datanum.put("pathfinder_eqv", rs.getString("pathfinder_potential_eqv"));
datanum.put("pathfinder_obs", rs.getString("pathfinder_observation"));
datanum.put("pathfinder_quick", rs.getString("pathfinder_quickwin"));
datanum.put("pathfinder_idea_id", rs.getString("idea_id"));
datanum.put("pathfinder_benefit", rs.getString("benefit_id"));
datanum.put("pathfinder_closure", rs.getString("pathfinder_target_closure"));
prolist.add(datanum);
}
z = "Success";
}
} catch (Exception ex) {
z = "Error retrieving data from table";
Log.e("MYAPP", "exception", ex);
}
return z;
}
}
}
Check this out i believe its much more close to the new design guidelines!!!
You can create your own adapter and customise list item.
here is a tutorial about list view.
for your questions. chapter 15 might be what you have been looking for.
http://www.vogella.com/tutorials/AndroidListView/article.html#listview_selection
hope this help !!!
How can i pass the position of item using intent to start a new activity?
I want to start a new activity called single which displays the rating of the movie correspondingly..pls help
I have been trying this for the past two days.
Here is the code:
public class NowPlaying extends Fragment {
private static final String TAG = NowPlaying.class.getSimpleName();
// Movies json url
private static final String url = "http://private-8149-themoviedb.apiary-mock.com/3/movie/now_playing?api_key=";
private ProgressDialog pDialog;
private List<NowPlayingInfo> bottom = new ArrayList<NowPlayingInfo>() ;
NowPlayingAdapter adapter;
RecyclerView recyclerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_main, container, false);
ActionBar toolbar = ((AppCompatActivity) getActivity()).getSupportActionBar();
toolbar.setTitle("Now playing");
recyclerView = (RecyclerView) v.findViewById(R.id.cardList);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(linearLayoutManager);
adapter = new NowPlayingAdapter(getActivity(), bottom);
recyclerView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.show();
adapter.SetOnItemClickListener(new NowPlayingAdapter.OnItemClickListener() {
#Override
public void onItemClick(View v, int position) {
// do something with position
Intent i = new Intent(v.getContext(), Single.class);
//pass the position of the item to single class
v.getContext().startActivity(i);
}
});
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
hidePDialog();
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
NowPlayingInfo trailer = new NowPlayingInfo();
trailer.setTitle(jsonObject.getString("original_title"));
String iss = "http://image.tmdb.org/t/p/w500" + jsonObject.getString("poster_path") ;
trailer.setImage(iss);
bottom.add(trailer);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
return v;
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
adapter.SetOnItemClickListener(new NowPlayingAdapter.OnItemClickListener() {
#Override
public void onItemClick(View v, int position) {
NowPlayingInfo _nowPlaying = bottom.get(position);
// do something with position
Intent i = new Intent(v.getContext(), Single.class);
//pass the position of the item to single class
i.putExtra("ISS", _nowPlaying.getImage()); //you can put your current playing info.
i.putExtra("POSITION", position); //you can put your position to next activity.
v.getContext().startActivity(i);
}
});
Add this in your SingleInfo Class.
String _rating = "";
public String get_rating() {
return _rating;
}
public void set_rating(String _rating) {
this._rating = _rating;
}
Add this in your Single class -
int _currentPos = 0 ; //Global variable .
_currentPos = getIntent().getIntExtra("position", 0);// paste this in onCreate()
Add this code in onResponse of Single Class -
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
SingleInfo s = new SingleInfo();
s.set_rating(jsonObject.getString("rating"));
single.add(s);
}
//changed by Shoeb
SingleInfo _singleInfo = single.get(_currentPos); //position from previous activity
textView.setText(_singleInfo.get_rating());
//end changes
} catch (JSONException e) {
e.printStackTrace();
}
Add an extra to your intent
i.putExtra("position",position);
And on the other activity:
getIntent().getIntExtra("position", 0);
I know there are many questions asking about returning to the last position scrolled when the list has been refreshed. However I don't know why in my case (Adapter) the given answers don't work.
I have an adapter where at a given time it refreshes with new info and loads it in the adapter. What I want is that when it refreshes not come again to the top of the adapter and save the previous state.
Here is the code I use.
OnCreate
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_candidatos);
if (Titulacion.IsReachable1(getApplicationContext())){
new CargarCandidatos().execute();
timer();
}else{
Toast.makeText(getApplicationContext(), R.string.errorserver, Toast.LENGTH_LONG).show();
}
setListAdapter(adapter);
candidatosList = new ArrayList<HashMap<String, String>>();
The asynctask is divided in 2 parts. The retrieval of information and adapting the data into the adapter.
Here is the code of adapting it:
protected void onPostExecute(String file_url) {
runOnUiThread(new Runnable() {
public void run() {
adapter = new SimpleAdapter(
Monitorizacion.this, candidatosList,
R.layout.list_item, new String[] { TAG_ID,TAG_NSERIE,TAG_TABLET,
TAG_DNI, TAG_NOMBRE, TAG_TEST, TAG_PREGUNTA, TAG_BATERIA,TAG_CORRECTAS, TAG_ERRORES},
new int[] { R.id.autoid,R.id.id,R.id.tablet, R.id.dni, R.id.nombre, R.id.test, R.id.pregunta, R.id.bateria, R.id.correctas, R.id.fallos});
adapter.notifyDataSetChanged();
setListAdapter(adapter);
}
});
}
But how should I save the state of the adapter and then start showing the items considering the previous state.
Thank you
Edit: I have tried the answer approbed here Maintain/Save/Restore scroll position when returning to a ListView, but I cannot make it work.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_candidatos);
if (Titulacion.IsReachable1(getApplicationContext())){
new CargarCandidatos().execute();
timer();
}else{
Toast.makeText(getApplicationContext(), R.string.errorserver, Toast.LENGTH_LONG).show();
}
setListAdapter(adapter);
candidatosList = new ArrayList<HashMap<String, String>>();
lv = (ListView)findViewById(android.R.id.list);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String idd = ((TextView) view.findViewById(R.id.dni)).getText()
.toString();
Intent in = new Intent(getApplicationContext(),
MonitDetail.class);
in.putExtra("idd", idd);
startActivityForResult(in, 100);
}
});
}
//
//
public void timer(){
new CountDownTimer(tiempo, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
index = lv.getFirstVisiblePosition();
v = lv.getChildAt(0);
top = (v == null) ? 0 : v.getTop();
if (Titulacion.IsReachable1(getApplicationContext())){
new CargarCandidatos().execute();
timer();
}else{
Toast.makeText(getApplicationContext(), R.string.errorserver, Toast.LENGTH_LONG).show();
}
}
}.start();}
class CargarCandidatos extends AsyncTask<String, Void, String> {
protected String doInBackground(String... args) {
try {
monitorizar();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();}
return null;
}
protected void onPostExecute(String file_url) {
runOnUiThread(new Runnable() {
public void run() {
adapter = new SimpleAdapter(
Monitorizacion.this, candidatosList,
R.layout.list_item, new String[] { TAG_ID,TAG_NSERIE,TAG_TABLET,
TAG_DNI, TAG_NOMBRE, TAG_TEST, TAG_PREGUNTA, TAG_BATERIA,TAG_CORRECTAS, TAG_ERRORES},
new int[] { R.id.autoid,R.id.id,R.id.tablet, R.id.dni, R.id.nombre, R.id.test, R.id.pregunta, R.id.bateria, R.id.correctas, R.id.fallos});
lv.setSelectionFromTop(index, top);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
}
});
}
}
public void monitorizar() throws Exception{
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("fecha",Titulacion.fecha()));
JSONObject json = jParser.makeHttpRequest(url_candidatos, "GET", params);
ArrayList<HashMap<String, String>> temp;
temp = new ArrayList<HashMap<String, String>>();
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
candidatos = json.getJSONArray(TAG_CANDIDATOS);
for (int i = 0; i < candidatos.length(); i++) {
JSONObject c = candidatos.getJSONObject(i);
String id = c.getString(TAG_ID);
String nserie = c.getString(TAG_NSERIE);
String tablet = c.getString(TAG_TABLET);
String dni = c.getString(TAG_DNI);
String nombre = c.getString(TAG_NOMBRE);
String test = c.getString(TAG_TEST);
String pregunta = c.getString(TAG_PREGUNTA);
String bateria = c.getString(TAG_BATERIA);
String correctas = c.getString(TAG_CORRECTAS);
String errores = c.getString(TAG_ERRORES);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, id);
map.put(TAG_NSERIE, nserie);
map.put(TAG_TABLET, tablet);
map.put(TAG_DNI, dni);
map.put(TAG_NOMBRE, nombre);
map.put(TAG_TEST, test);
map.put(TAG_PREGUNTA, pregunta);
map.put(TAG_BATERIA, bateria);
map.put(TAG_CORRECTAS, correctas);
map.put(TAG_ERRORES, errores);
temp.add(map);
candidatosList = temp;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
You can use like this
getListView().setSelection(position);
method of your ListView.
where you can get 'position' from the length of list you are passing to the adapter.
Declare you listview Globally and then you can keep the last position before New-Data-call. After then you can call listview for a position selection.