I keep a school project dealing with a ListView filled with images hosted on a server.
When someone selects an image from the list, this is shown by "original" size in another layout and even here everything went well.
But also ask when the image display have the option to save it to the SD Card and that's the part I can not do.
This is the code I did:
public class MainActivity extends AppCompatActivity {
private ListView listView;
private ProgressDialog progressDialog;
ArrayList asuntos=new ArrayList();
ArrayList imagen=new ArrayList();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolBar);
listView=(ListView) findViewById(R.id.list);
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
lista o=new lista();
o.obtenerAvisos();
}
public class lista {
public void obtenerAvisos() {
asuntos.clear();
imagen.clear();
String tag_string_req = "req_data";
progressDialog.setMessage("Conectando...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST, AppURLs.URL, new Response.Listener<String>() {
public void onResponse(String response) {
hideDialog();
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
asuntos.add(jsonArray.getJSONObject(i).getString("asunto"));
imagen.add(jsonArray.getJSONObject(i).getString("publicacion"));
}
listView.setAdapter(new ImagenAdaptador(getApplicationContext()));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "data");
return params;
}
};
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
public class ImagenAdaptador extends BaseAdapter {
Context ctx;
LayoutInflater layoutInflater;
SmartImageView smartImageView;
TextView tvasunto;
public ImagenAdaptador(Context applicationContext) {
this.ctx=applicationContext;
layoutInflater=(LayoutInflater)ctx.getSystemService(LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return imagen.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewGroup viewGroup=(ViewGroup) layoutInflater.inflate(R.layout.activity_main_items,null);
smartImageView=(SmartImageView)viewGroup.findViewById(R.id.imagen1);
tvasunto=(TextView) viewGroup.findViewById(R.id.tvAsunto);
final String urlfinal="http://192.168.43.45/InfoTec/publicaciones/"+imagen.get(position).toString();
Rect rect=new Rect(smartImageView.getLeft(), smartImageView.getTop(), smartImageView.getRight(), smartImageView.getBottom());
smartImageView.setImageUrl(urlfinal, rect);
tvasunto.setText(asuntos.get(position).toString());
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, Visor.class);
intent.putExtra("arg", asuntos.get(position).toString());
intent.putExtra("arg2",imagen.get(position).toString());
startActivity(intent);
}
});
return viewGroup;
}
}
}
This part works, but this class is the problem:
public class Visor extends AppCompatActivity {
TextView tvasunto2;
SmartImageView smartImageView2;
Button descarga;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visor);
String original=getIntent().getStringExtra("arg");
String imgOriginal=getIntent().getStringExtra("arg2");
tvasunto2=(TextView) findViewById(R.id.tvAsunto2);
smartImageView2=(SmartImageView) findViewById(R.id.imagen2);
descarga=(Button) this.findViewById(R.id.button);
tvasunto2.setText(original);
String url="http://192.168.43.45/InfoTec/publicaciones/"+imgOriginal;
Rect rect=new Rect(smartImageView2.getLeft(), smartImageView2.getTop(), smartImageView2.getRight(), smartImageView2.getBottom());
smartImageView2.setImageUrl(url,rect);
descarga.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
If the selected image is displayed, but not now how to handle the data in the event the download button.
What would be the solution?
First, you need to get your Bitmap. You can already have it as an object Bitmap, or you can try to get it from the ImageView such as:
BitmapDrawable drawable = (BitmapDrawable) mImageView1.getDrawable();
Bitmap bitmap = drawable.getBitmap();
Then you must get to directory (a File object) from SD Card such as:
File sdCardDirectory = Environment.getExternalStorageDirectory();
Next, create your specific file for image storage:
File image = new File(sdCardDirectory, "test.png");
After that, you just have to write the Bitmap thanks to its method compress such as:
boolean success = false;
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Finally, just deal with the boolean result if needed. Such as:
if (success) {
Toast.makeText(getApplicationContext(), "Image saved with success",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_LONG).show();
}
Don't forget to add the following permission in your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
It will be better to create a Dialog to let the user select where they want the photo to be store at. Remember there are a ton of android devices and they might vary.
Related
I have made a discussion forum where the person who is logged in can ask a question and the main forum shows all the question put up by a different user. everyone can answer the question also and rate.
The problem is when is add the question from adding question activity it is going back to discussion forum but not refreshing. What I want is as soon as the question is asked, it should show in the discussion forum and the user should have the ability to modify and delete that question. everything is dynamic how to delete the dynamic data as well.
this is my discussion forum code
package com.example.pitechnologies.pkguru.fragment;
public class DiscussionForumFragment extends Fragment {
TextView title;
RelativeLayout askquestion;
public View view;
UserProfileData userProfileData;
String U_id;
EditText que, desc;
TextView btnask;
String uname;
LinearLayout linearLayout;
ImageView imgSpoon;
final List<Model_Forum> unilist = new ArrayList<>();
private static String TAG = DiscussionForumFragment.class.getSimpleName();
private RecyclerView forumrecyclerView;
private ForumList_Adapter forumAdapter;
public DiscussionForumFragment() {
}
#Override
public void onStart() {
((AppCompatActivity) getActivity()).getSupportActionBar().hide();
super.onStart();
}
#Override
public void onResume() {
super.onResume();
((AppCompatActivity) getActivity()).getSupportActionBar().hide();
// forumdata();
}
#Override
public void onStop() {
super.onStop();
((AppCompatActivity) getActivity()).getSupportActionBar().show();
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_discussion_forum, container, false);
title = (TextView) view.findViewById(R.id.forumtitle);
title.setText("DISCUSSION FORUM");
askquestion = (RelativeLayout) view.findViewById(R.id.askquestion);
askquestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(PreferenceHelper.getInstance(getActivity()).getSemid() == null) {
Intent intent = new Intent(getActivity(), ActivityLoginSignUp.class);
startActivity(intent);
}else {
Intent intent = new Intent(getActivity(), ActivityQuestionaire.class);
intent.putExtra("uu_id", U_id);
startActivity(intent);
}
}
});
forumrecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview_forum);
forumrecyclerView.setHasFixedSize(true);
forumrecyclerView.setLayoutManager(new LinearLayoutManager(DiscussionForumFragment.this.getActivity()));
forumAdapter = new ForumList_Adapter(DiscussionForumFragment.this.getContext(), unilist);
forumrecyclerView.setAdapter(forumAdapter);
forumrecyclerView.setNestedScrollingEnabled(false);
imgSpoon = (ImageView) view.findViewById(R.id.image_spoon);
linearLayout = (LinearLayout) view.findViewById(R.id.pg_loader);
linearLayout.setVisibility(View.INVISIBLE);
forumdata();
return view;
}
public void forumdata() {
unilist.clear();
/* final ProgressDialog pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.show();*/
linearLayout.setVisibility(View.VISIBLE);
ObjectAnimator flip = ObjectAnimator.ofFloat(imgSpoon, "rotationY", 0f, 180f);
flip.setDuration(800);
flip.setRepeatCount(Animation.INFINITE);
flip.start();
StringRequest strReq = new StringRequest(Request.Method.POST,
URLconstant.FORUM, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
try {
JSONObject data = new JSONObject(response);
Log.d("data", data.toString());
JSONArray datarray = data.getJSONArray("data");
for (int i = 0; i < datarray.length(); i++) {
JSONObject secondobj = datarray.getJSONObject(i);
Log.d("secondobj", secondobj.toString());
Model_Forum model_forum = new Model_Forum();
model_forum.mforum_id = secondobj.getString("forum_id");
model_forum.mqst = secondobj.getString("qst");
model_forum.mqst_description = secondobj.getString("qst_description");
model_forum.mqst_uid = secondobj.getString("qst_uid");
model_forum.muser_id = secondobj.getString("user_id");
model_forum.mfullname = secondobj.getString("fullname");
model_forum.muniver_id = secondobj.getString("univer_id");
model_forum.mbranchid = secondobj.getString("branchid");
model_forum.msemid = secondobj.getString("semid");
model_forum.mcollegeid = secondobj.getString("collegeid");
model_forum.muser_image = secondobj.getString("user_image");
model_forum.mq_date = secondobj.getString("q_date");
model_forum.mq_time = secondobj.getString("q_time");
unilist.add(model_forum);
}
if (getContext() != null) {
/* forumAdapter = new ForumList_Adapter(DiscussionForumFragment.this.getContext(), unilist);
forumrecyclerView.setAdapter(forumAdapter);*/
forumAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
// pDialog.dismiss();
linearLayout.setVisibility(View.INVISIBLE);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
// pDialog.dismiss();
linearLayout.setVisibility(View.INVISIBLE);
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(strReq);
}
I have a videoview and listview/gridview in my playvideo activity.
One video is already playing in the videoview. But now i want to play the other video which are showing in the listview/gridview how can i do that?
Playvideo Activity
public class playvideoactivity extends Activity {
GridViewWithHeaderAndFooter grid;
String videourl="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4";
private static final String url = "http://dakwf.org/api/bd_english.json";
private List<ChannelItem> chanellist = new ArrayList<ChannelItem>();
private static final String TAG = MainActivity.class.getSimpleName();
public static VideoView player;
public static ImageButton btnPlayPause;
private ImageView btnFullscreen;
private ProgressBar spinner;
private RelativeLayout mediaController;
private Handler btnHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (ProgressBar) findViewById(R.id.progressBar);
player=(VideoView) findViewById(R.id.player);
mediaController=(RelativeLayout) findViewById(R.id.media_controller);
spinner.setVisibility(View.VISIBLE);
mediaController.setVisibility(View.INVISIBLE);
btnPlayPause=(ImageButton) findViewById(R.id.btn_playpause);
btnFullscreen=(ImageView) findViewById(R.id.btn_fullscreen);
final CustomGridviewadapter customGridview= new CustomGridviewadapter(this,chanellist);
grid = (GridViewWithHeaderAndFooter) findViewById(R.id.grid_view);
setGridViewHeaderAndFooter();
grid.setAdapter(customGridview);
//----------- Creating volley request obj--------------------
JsonArrayRequest movieReq = new JsonArrayRequest(url,new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
ChannelItem item = new ChannelItem();
item.setTitle(obj.getString("title"));
item.setThumbnailUrl(obj.getString("image"));
// adding movie to movies array
chanellist.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
customGridview.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
//------------------- Mediacontroller Visiblity-------------------------------------
player.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(final View paramAnonymousView, MotionEvent paramAnonymousMotionEvent)
{
if (paramAnonymousMotionEvent.getAction() == 0){
if (MainActivity.this.mediaController.getVisibility() != View.INVISIBLE) {
}
MainActivity.this.mediaController.setVisibility(View.VISIBLE);
MainActivity.this.btnHandler.postDelayed(new Runnable(){
public void run(){
MainActivity.this.mediaController.setVisibility(View.INVISIBLE);
}
}, 2000L);
}
for (;;){
return true;
}
}
});
//------FullScreen Button -----
btnFullscreen.setOnClickListener(new View.OnClickListener(){
public void onClick(View paramAnonymousView) {
Intent i = new Intent(MainActivity.this, FullScreenView.class);
startActivity(i);
}
});
//------Play Pause Button ----------
btnPlayPause.setOnClickListener(new View.OnClickListener() {
public void onClick(View paramAnonymousView){
if ( (player != null) && (MainActivity.this.player.isPlaying()) ){
MainActivity.this.player.pause();
MainActivity.this.btnPlayPause.setBackgroundResource(R.drawable.btn_play);
return;
}
MainActivity.this.player.start();
MainActivity.this.btnPlayPause.setBackgroundResource(R.drawable.btn_pause);
return;
}
});
//----------------------------------------
try {
MediaController mController = new MediaController(MainActivity.this);
mController.setAnchorView(player);
Uri video = Uri.parse(videourl);
player.setMediaController(mController);
player.setVideoURI(video);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
player.setMediaController(null);
player.requestFocus();
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer arg0) {
player.start();
hidespinner();
}
});
}
// ------------ Header Gridview ----------------
#SuppressLint({"InflateParams", "SetTextI18n"})
private void setGridViewHeaderAndFooter() {
LayoutInflater layoutInflater = LayoutInflater.from(this);
View headerView = layoutInflater.inflate(R.layout.grid_header, null, false);
//locate views
TextView headerText = (TextView)headerView.findViewById(R.id.textViewheader);
headerText.setText("Suggestion");
headerView.setOnClickListener(onClickListener(0));
grid.addHeaderView(headerView);
}
private View.OnClickListener onClickListener(final int i) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
if (i == 0) {
// Toast.makeText(MainActivity.this, "Header Clicked!", Toast.LENGTH_SHORT).show();
} else {
// Toast.makeText(MainActivity.this, "Footer Clicked!", Toast.LENGTH_SHORT).show();
}
}
};
}
#Override
public void onDestroy() {
super.onDestroy();
hidespinner();
}
private void hidespinner() {
if (spinner != null) {
spinner.setVisibility(View.INVISIBLE);
spinner = null;
}
}
}
When opening starting the app you need to get the data and store on a variable or into database.
Create a ChannelList type List (List<ChannelList>) and store ChannelList data into it.
List<ChannelList> list = new ArrayList<>(); // containing all data
You can store Title, VideoUrl, iconUrl and add it to the list.
When clicking on a List Item you will get the position by using setOnItemClickListener.
And then use the position to get the clicked ChannelList position.
Suppose your list type variable is channelList.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ChannelList channelList= list.get(position);
// now you have all data of clicked ChannelList
// do whatever you like
//channelList.getVideoUrl(); etc as your getter method
}
}
});
For more about List, you can check it Here
This question already has answers here:
How to save custom ArrayList on Android screen rotate?
(4 answers)
Closed 6 years ago.
I have an ArrayList with custom json objects fetched from the web with Volley. I would like to be able to save and restore these objects on a screen rotate. I would also like to save and restore my current scrolled position on screen rotate.
I have a sketchy idea that this can be done with onSaveInstanceState and onRestoreInstanceState?
Activity Code
public class MainActivity extends AppCompatActivity {
private final String TAG = "MainActivity";
//Creating a list of posts
private List<PostItems> mPostItemsList;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "Device rotated and onCreate called");
//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.post_recycler);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Initializing the postlist
mPostItemsList = new ArrayList<>();
adapter = new PostAdapter(mPostItemsList, this);
recyclerView.setAdapter(adapter);
if (NetworkCheck.isAvailableAndConnected(this)) {
//Caling method to get data
getData();
} else {
final Context mContext;
mContext = this;
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(R.string.alert_titl);
alertDialogBuilder.setMessage(R.string.alert_mess);
alertDialogBuilder.setPositiveButton(R.string.alert_posi, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!NetworkCheck.isAvailableAndConnected(mContext)) {
alertDialogBuilder.show();
} else {
getData();
}
}
});
alertDialogBuilder.setNegativeButton(R.string.alert_nega, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialogBuilder.show();
}
}
//This method will get data from the web api
private void getData(){
Log.d(TAG, "getData called");
//Showing progress dialog
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setCancelable(false);
mProgressDialog.setMessage(this.getResources().getString(R.string.load_post));
mProgressDialog.show();
//Creating a json request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigPost.GET_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called");
//Dismissing the progress dialog
if (mProgressDialog != null) {
mProgressDialog.hide();
}
/*progressDialog.dismiss();*/
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
PostItems postItem = new PostItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
postItem.setPost_title(jsonObject.getString(ConfigPost.TAG_POST_TITLE));
postItem.setPost_body(jsonObject.getString(ConfigPost.TAG_POST_BODY));
} catch (JSONException w) {
w.printStackTrace();
}
mPostItemsList.add(postItem);
}
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy called");
if (mProgressDialog != null){
mProgressDialog.dismiss();
Log.d(TAG, "mProgress dialog dismissed");
}
}
Thanks in advance.
Note a duplicate of How to save custom ArrayList on Android screen rotate?. While the arraylist in that question is declared in the Activity, mine is fetched with volley from the web. I don't know how to implement it for my arraylist, else this question wouldn't be asked
This is, in fact, a duplicate of the post you mentioned. Yes, the list was declared in the activity's onCreate() in that post, whereas you are doing it asynchronously. However, the idea is the same.
Once you have data to send, at any point of your application, it can be saved and restored.
The key, in your case, is to not call getData() every time the device is rotated. If you already have data loaded in mPostItemsList, then save and restore it via onSaveInstanceState(), and in onCreate() you get the data from the saved state. If that data does not exist, then you call getData().
public class MainActivity extends AppCompatActivity {
private final String TAG = "MainActivity";
private final String KEY_POST_ITEMS = "#postitems";
//Creating a list of posts
private List<PostItems> mPostItemsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeViews();
if (savedInstanceState != null && savedInstanceState.containsKey(KEY_POST_ITEMS)){
mPostItemsList = savedInstanceState.getParcelableArrayList(KEY_POST_ITEMS);
} else {
//Initializing the postlist
mPostItemsList = new ArrayList<>();
if (NetworkCheck.isAvailableAndConnected(this)) {
//Caling method to get data
getData();
} else {
showNoNetworkDialog();
}
}
mAdapter = new PostAdapter(mPostItemsList, this);
recyclerView.setAdapter(adapter);
}
private void parseData(JSONArray array){
mPostItemsList.clear();
for(int i = 0; i<array.length(); i++) {
PostItems postItem = new PostItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
postItem.setPost_title(jsonObject.getString(ConfigPost.TAG_POST_TITLE));
postItem.setPost_body(jsonObject.getString(ConfigPost.TAG_POST_BODY));
} catch (JSONException w) {
w.printStackTrace();
}
mPostItemsList.add(postItem);
}
mAdapter.notifyDataSetchanged();
}
Edit: I didn't see the requirement to save scroll position. Look at Emin Ayar's answer for that. Also, a similar answer for it is also here: How to save recyclerview scroll position.
You can use onConfigurationChanged at your activity to detect rotation changes. Also you should track lastVisibleItemPosition with layoutManager.findLastVisibleItemPosition() and when rotation changed you should scroll to this position. You will need to use recyclerView.setOnScrollListener() to listen scrolls to keep your lastVisibleItemPosition updated
public class MainActivity extends AppCompatActivity {
private final String TAG = "MainActivity";
//Creating and initializing list of posts
private List<PostItems> mPostItemsList = new ArrayList<>();;
//Creating Views
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ProgressDialog mProgressDialog;
private int lastVisibleItemPos = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "Device rotated and onCreate called");
if (NetworkCheck.isAvailableAndConnected(this)) {
//Caling method to get data and check if postList have value set before or not
// because this part will be called on every rotation change, we are controlling this
if (mPostItemsList.size() <= 0) {
//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.post_recycler);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
adapter = new PostAdapter(mPostItemsList, this);
recyclerView.setAdapter(adapter);
getData();
}
} else {
final Context mContext;
mContext = this;
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(R.string.alert_titl);
alertDialogBuilder.setMessage(R.string.alert_mess);
alertDialogBuilder.setPositiveButton(R.string.alert_posi, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!NetworkCheck.isAvailableAndConnected(mContext)) {
alertDialogBuilder.show();
} else {
getData();
}
}
});
alertDialogBuilder.setNegativeButton(R.string.alert_nega, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialogBuilder.show();
}
}
//This method will get data from the web api
private void getData(){
Log.d(TAG, "getData called");
//Showing progress dialog
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setCancelable(false);
mProgressDialog.setMessage(this.getResources().getString(R.string.load_post));
mProgressDialog.show();
//Creating a json request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigPost.GET_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called");
//Dismissing the progress dialog
if (mProgressDialog != null) {
mProgressDialog.hide();
}
/*progressDialog.dismiss();*/
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//This method will parse json data
private void parseData(JSONArray array){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
PostItems postItem = new PostItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
postItem.setPost_title(jsonObject.getString(ConfigPost.TAG_POST_TITLE));
postItem.setPost_body(jsonObject.getString(ConfigPost.TAG_POST_BODY));
} catch (JSONException w) {
w.printStackTrace();
}
mPostItemsList.add(postItem);
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// set your adapter here with your data
adapter = new PostAdapter(mPostItemsList, this);
recyclerView.setAdapter(adapter);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy called");
if (mProgressDialog != null){
mProgressDialog.dismiss();
Log.d(TAG, "mProgress dialog dismissed");
}
}
Here is my main activity Collegelist with the contents already loaded from the database but i have only displayed the name.When i click on the name i want to show the name,address and contact on different activity.
public class Collegelist extends ActionBarActivity {
HTTPConnection http;
List<Colleges> college = new ArrayList<Colleges>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.college_list);
http = new HTTPConnection(getApplicationContext());
if (http.isNetworkConnection()) {
//String data = http.HTTPGetData("http://localhost/minorproject/show.php");
//Toast.makeText(getApplicationContext(),data ,Toast.LENGTH_LONG).show();
task.execute();
}
else {
Toast.makeText(getApplicationContext(), "check your connection",
Toast.LENGTH_LONG).show();
}
}
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String data = http.HTTPGetData("http://localhost/college/show.php");
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
populateList(result);
displayList();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
};
protected void populateList(String result) {
try {
//Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
JSONObject jobj = new JSONObject(result);
String res = jobj.getString("success");
if (!res.equals("true")) {
Toast.makeText(getApplicationContext(), "JSON Error",
Toast.LENGTH_LONG).show();
return;
}
else
{
JSONArray data = jobj.getJSONArray("msg");
// Toast.makeText(getApplicationContext(),"successss",Toast.LENGTH_SHORT).show();
for (int i = 0; i < data.length(); i++) {
JSONObject col = data.getJSONObject(i);
Colleges cg = new Colleges(col.getString("cname"), col.getString("caddress"), col.getString("ccontact_a"));
college.add(cg);
}
}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
protected void displayList() {
ArrayAdapter<Colleges> adapter = new ArrayAdapter<Colleges>(this, R.layout.list_item,college){
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = getLayoutInflater().inflate(R.layout.list_item,null);
//set values
Colleges c = college.get(position);
((TextView)view.findViewById(R.id.name)).setText(c.getName());
/* ((TextView)view.findViewById(R.id.address)).setText(c.getAddress());
((TextView)view.findViewById(R.id.contact)).setText(c.getContact());
*/
return view;
}
};
final ListView collegelistnew = (ListView) findViewById(R.id.listView);
collegelistnew.setAdapter(adapter);
collegelistnew.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
/*Toast.makeText(
getApplicationContext(),
"You clicked position" + position + "with item name"
+ college.get(position).getName(),
Toast.LENGTH_LONG).show();*/
Intent newIntent =new Intent(getApplicationContext(),CollegeDetails.class);
newIntent.putExtra("college", (Serializable) college.get(position));
startActivity(newIntent);
}
});
}}
Uncomment these two lines :
/* ((TextView)view.findViewById(R.id.address)).setText(c.getAddress());
((TextView)view.findViewById(R.id.contact)).setText(c.getContact());
*/
Then set their visibility to GONE using:
((TextView)view.findViewById(R.id.address)).setVisibility(View.GONE);
((TextView)view.findViewById(R.id.contact)).setVisibility(View.GONE);
or using xml.
And in this way you can show only one name in your list view but you get the address and contact also to carry on to another activty.
That class seems to be OK. However you should make your class Collegesto implement Parcelableinterface.
The error must be in CollegeDetails class
I have a program with a screen that has about 50 buttons, it looks rather ugly. Each button has an async download in it, it is just copied from button to button with the URL and file name saved as changed. I want to be able to change from using buttons to using one spinner, hopefully with just one async download task and the spinner operating as the way to select the download URL and the filename to save as. Is this even possible? After reading some documentation about it I got confused. Thanks for the help.
Update:
With the suggested code from below I created this:
public class SpinnerActivity extends Activity{
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
Spinner spDownloadFrom;
private ArrayAdapter<CharSequence> spinnerArrayAdapter;
String url[]= {"www.abc.com/download/a.txt",
"www.abc.com/download/a.txt",
"www.abc.com/download/a.txt",
"www.abc.com/download/a.txt",
"www.abc.com/download/a.txt",
"www.abc.com/download/a.txt",
"www.abc.com/download/a.txt"
};
String links[]= {"Server 1",
"Server 2",
"Server 3",
"Server 4",
"Server 5",
"Server 6",
"Server 7",
};
public void onCreate(Bundle savedInstanceState )
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mProgressDialog = new ProgressDialog(SpinnerActivity.this);
mProgressDialog.setMessage("Please be patient, file downloading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
spDownloadFrom=(Spinner)findViewById(R.id.Spinner01);
spinnerArrayAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, links);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spDownloadFrom.setAdapter(spinnerArrayAdapter);
spDownloadFrom.setOnItemSelectedListener(new SpinnerListener(spDownloadFrom));
}
public class SpinnerListener implements OnItemSelectedListener
{
Spinner sp;
public SpinnerListener(View v)
{
sp=(Spinner)findViewById(v.getId());
}
#Override
public void onItemSelected(AdapterView<?> arg0, View v, int arg2,
long arg3) {
//Call to download class
new DownloadFile().equals(url[arg2].toString());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
class DownloadFile extends AsyncTask<String, Integer, String> { //put your download code
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setProgress(progress[0]);
}
#Override
protected String doInBackground(String... aurl) {
try {
URL url = new URL(aurl[0]);
URLConnection connection = url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
int tickSize = 2 * fileLength / 100;
int nextProgress = tickSize;
Log.d(
"ANDRO_ASYNC", "Lenght of file: " + fileLength);
InputStream input = new BufferedInputStream(url.openStream());
String path = Environment.getExternalStorageDirectory()
+ "/Android/Data/"
+ getApplicationContext().getPackageName() + "/files";
File file = new File(path);
file.mkdirs();
File outputFile = new File(file, "test1.pdf");
OutputStream output = new FileOutputStream(outputFile);
byte data[] = new byte[1024 * 1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
if (total >= nextProgress) {
nextProgress = (int) ((total / tickSize + 1) * tickSize);
this.publishProgress((int) (total * 100 / fileLength));
}
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
mProgressDialog.dismiss();
} catch (Exception e) {
}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("Downloading",progress[0]);
}
#Override
protected void onPostExecute(String unused) {
File file = new File(Environment.getExternalStorageDirectory()
+ "/Android/Data/" + getApplicationContext().getPackageName()
+ "/files/test1.pdf");
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(SpinnerActivity .this,
"No Application Available to View PDF", Toast.LENGTH_LONG).show();
}
}
}
}
Is this correct for what I am trying to accomplish?
public class Example extends Activity{
Spinner spDownloadFrom;
private ArrayAdapter<CharSequence> spinnerArrayAdapter;
String url[]= {"www.abc.com/download/a.txt",
"www.abc.com/download/a.txt",
"www.abc.com/download/a.txt",
"www.abc.com/download/a.txt",
"www.abc.com/download/a.txt",
"www.abc.com/download/a.txt",
"www.abc.com/download/a.txt"
};
String links[]= {"Server 1",
"Server 2",
"Server 3",
"Server 4",
"Server 5",
"Server 6",
"Server 7",
};
public void onCreate(Bundle savedInstanceState )
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spDownloadFrom=(Spinner)findViewById(R.id.addQuotation_spinnerProduct);
spinnerArrayAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, links);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spDownloadFrom.setAdapter(spinnerArrayAdapter);
spDownloadFrom.setOnItemSelectedListener(new SpinnerListener(spDownloadFrom));
}
public class SpinnerListener implements OnItemSelectedListener
{
Spinner sp;
public SpinnerListener(View v)
{
sp=(Spinner)findViewById(v.getId());
}
#Override
public void onItemSelected(AdapterView<?> arg0, View v, int arg2,
long arg3) {
//Call to download class
new DownloadFile().equals(url[arg2].toString());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
class DownloadFile extends AsyncTask<String, String, String> { //put your download code
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... aurl) {
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("Downloading",progress[0]);
}
#Override
protected void onPostExecute(String unused) {
}
}
}
It is a sample class to meet your requirement. I did not run it so sorry if there is some mistake, but basic idea is here.
Very possible. Set your data into an array and create the spinner. While true that a spinner doesn't support click events, it does do selection, so you would have some code like this after you create the spinner:
yourSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Nothing to do here
}
#Override
public void onItemSelected(AdapterView<?> parent, View view,int pos, long id) {
// Your code to get the URL and filename here
}
});
You could have it fire immediately upon selection by putting all the code necessary in the onItemSelected, or just set some variables there and then have a button in your layout (outside of the spinner) to take the variables you set and kick off the online activities. The second option lets the user change their mind without starting unwanted online activity.
Hope this helps.