How to create a custom Progress Dialog(spinner)? - android

I have googled a lot and even gone through many of this website questions but I just can't find the solution to my problem.
I want to create a spinner like the one below. This is just a normal spinner I have done till now. I tried a variety of spinner examples but they don't give me my desired result.
Here is my code:
public class nextclass extends Activity {
Thread t;
ProgressBar dia;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
MainActivity.progressDialog.dismiss();
setContentView(R.layout.nextclassview);
// requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
((Button) findViewById(R.id.button1))
.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// progressDialog = findViewById(R.id.progressBar1);
new AuthenticateUserTask().execute();
}
});
}
private class AuthenticateUserTask extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = ProgressDialog.show(
nextclass.this, "","Sucessful", true);
/* progressDialog.setIndeterminate(true);
progressDialog.setIndeterminateDrawable(getResources()
.getDrawable(R.layout.customspinner));
*/
progressDialog = ProgressDialog.show(nextclass.this, "",
"Processing....", true);
progressDialog.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
}
protected void onPostExecute(String s) {
if (progressDialog.isShowing())
progressDialog.dismiss();
Intent my = new Intent(getApplicationContext(), CountTime.class);
startActivity(my);
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
Thread.sleep(2000);![custom spinner][2]
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
}

I Don't have Seen any Spinner in your Code. but Anyway you can use below code for making Custom Spinner.
Inside your Layout File:
<Spinnerandroid:id="#+id/spinnerview"
android:layout_width="180dp"
android:layout_height="42dp"
android:layout_marginLeft="105dp"
android:layout_marginTop="45dp"
android:background="#drawable/spinner_back"
android:paddingLeft="5dp"
android:spinnerMode="dropdown"android:visibility="visible" />
inside your String.xml :
<string-array name="spinner_array_environtment">
<item>Test</item>
<item>Production</item>
</string-array>
inside you Java File in OnCreate Method:
spinner_environment = (Spinner) findViewById(R.id.spinnerview);
adapter = ArrayAdapter.createFromResource(this,
R.array.spinner_array_environtment, R.layout.spinner);
adapter.setDropDownViewResource(R.layout.spinner);
spinner_environment.setAdapter(adapter);
Make new spinner.xml file to your layout folder :
inside spinner.xml file :
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/spinnerTarget"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25dp"
android:textColor="#4C4646" />
Thats it!!!

Related

loading data from the list when android app open

Hi I just created app for loading data from the website once the button is clicked in android.I want to change the app for loading data when the application open.How will I do it?
Here is my code..
public class PrimaryActivity extends Activity {
private static final String URL = "http://livechennai.com/powershutdown_news_chennai.asp";
ProgressDialog mProgressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_primary);
Button btnFetchData = (Button) findViewById(R.id.btnData);
btnFetchData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new FetchWebsiteData().execute();
}
});
}
private class FetchWebsiteData extends AsyncTask<Void, Void, String[]> {
String websiteTitle, websiteDescription,websiteDescription1,websiteDescription2,websiteDescription3,listValue,listValue1;
ProgressDialog progress;
#Override
protected void onPreExecute() {
super.onPreExecute();
//some code here
}
#Override
protected String[] doInBackground(Void... params) {
ArrayList<String> hrefs=new ArrayList<String>();
try {
// parsing here
}
} catch (IOException e) {
e.printStackTrace();
}
//get the array list values
for(String s:hrefs)
{
//website data
}
//parsing first URL
} catch (IOException e) {
e.printStackTrace();
}
//parsing second URL
} catch (IOException e) {
e.printStackTrace();
}
try{
List<String> listString = new ArrayList<String>(Arrays.asList(resultArray));
listString.addAll(Arrays.asList(resultArray1));
String [] outResult= new String[listString.size()];
int i=0;
for(String str: listString){
outResult[i]=str;
i++;
}
return outResult;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] result) {
ListView list=(ListView)findViewById(R.id.listShow);
ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_list_item_1,result);
list.setAdapter(arrayAdapter);
mProgressDialog.dismiss();
}
}
}
How to load the list view when we open the app? help me to get the exact answer?
Just load it in onCreate. This is what will be called when the app is opened first. Then read about other events like onResume.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_primary);
new FetchWebsiteData().execute();
}
Call FetchWebsiteData().execute() from one of the activity lifecycle methods such as onStart, onCreate, or onResume - please refer to docs to determine which fits in your case.
Put the method which does the fetching i.e. new FetchWebsiteData().execute(); outside of the code of button click and in the activity.onResume() method.
onResume is called everytime an app comes to foreground, if you put it oncreate(), the method will be called only when the activity is created.

NullpointerException in onPreExcute of AsyncTask for ProgressBar

I had a NullPointerException when I try to set ProgessBar to visible in onPreExecute AsyncTask (mProgressBar.setVisibility(View.VISIBLE);). I don't know what went wrong! Thanks you all!
<ProgressBar
android:id="#+id/pb_featured_game_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
/>
public class MainActivity extends Activity {
...
private ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
new FetchGamesTask().execute();
private class FetchGamesTask extends
AsyncTask<Integer, Integer, List<GameInfo>> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
mProgressBar = (ProgressBar)findViewById(R.id.pb_featured_game_progress);
mProgressBar.setVisibility(View.VISIBLE);
}
Before you call the execute on your FetchGamesTask, you should associate the main view with the xml file.
Like this
protected void onCreate(Bundle savedInstanceState) {
// the OS will inflate the main_activity.xml
// file and use it for this activity
setContentView(R.layout.main_activity);
new FetchGamesTask().execute();

Error in simple AsyncTask

In my android app, I am trying to make use of ASYNC Task ... whenever I set text of any TextView of EditText in doInBackground(...) .... I get an error , but when I set the same in onCreate , it works .. :(
here is the code :
public class RemoteFiles extends Activity {
EditText etrmm ;
TextView t;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_remote_files);
initVars();
new ConnectToServer().execute(null);
}
protected void initVars(){
etrmm =(EditText)findViewById(R.id.etRM);
etrmm.setText("UnSET");
t=(TextView)findViewById(R.id.RM);
t.setText("UnsET");
}
public class ConnectToServer extends AsyncTask<String, Integer, Void> {
//private ProgressDialog pd = new ProgressDialog(RemoteFiles.this);
private ProgressDialog pdd ;
#Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub
for(int i=0;i<20;i++){
publishProgress(5);
try {
Thread.sleep(88);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
etrmm.setText("Edittext SET");
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pdd.dismiss();
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
// pd.setMessage("Connecting to server... ");
// pd.show();
pdd = new ProgressDialog(RemoteFiles.this);
pdd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pdd.setMax(100);
pdd.show();
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
pdd.incrementProgressBy(values[0]);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_remote_files, menu);
return true;
}}
here is the layout :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/RM"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="#dimen/padding_medium"
android:text="#string/hello_world"
tools:context=".RemoteFiles" />
<EditText
android:id="#+id/etRM"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10" >
<requestFocus />
</EditText>
logcat says android.view.ViewRoot$CalledFromWrongThreadException
doInBackground(String... params) not run on UI Thread, so you can't set text for edittext there
if you want to set edittext value, return the value in doInBackGround and use the parameter value in onPostExecute and set it in onPostExecute()
You can't do UI stuff in doInBackground(). This should be done in any of the other methods. For your purposes, probably onPostExecture()
Take a look at the AsyncDocs, doInBackground() doesn't run on the main (UI) thread
AsyncTask's onpreExecute and onPostExecute methods run o UI Thread. You can make changes to the UI here. doInBackground does not run on UI thread. It is used to do long Running operations. Runs in the background thread. You cannot update ui from the background thread in doinBackground.
Set text in textview in onPostExecute method of asynctask.
The document in the developer site has detailed information regarding the topic under the heading THE 4 STEPS. http://developer.android.com/reference/android/os/AsyncTask.html

Using 'Async Tasks' on Android to generate random number and output

I am writing an random number generator program to show the output every sec.
The overview is that every second when the random number change I would want to random number to be output to the 'EditText' box. Is it possible?
I have research on it but result in unsuccessfully (mainly because of how the async works).
This is the code that I have written:
package com.example;
import java.util.Random;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class AsyncTasksActivity extends Activity {
EditText txtMessage;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String ranString = "";
try{
ranString = "";
for(int a = 0; a < 33; a++)
{
Random rn = new Random();
int i = rn.nextInt(256);
ranString = ranString + i + " ";
}
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
txtMessage = (EditText) findViewById(R.id.txtMessage);
txtMessage.setText(ranString);
}
public class runRandomly extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(String... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
}
}
In case you need to run the code to ensure it works, I have place the xml code here:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Null"
/>
<EditText
android:id="#+id/Null"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:inputType="numberDecimal"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Random Key"/>
<EditText
android:id="#+id/txtMessage"
android:layout_width="fill_parent"
android:gravity="center"
android:editable="false" android:layout_height="61dp" android:layout_weight="0.14"/>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
Much Thanks!
From my point of view,
Make a constructor of your AsyncTask class passing activity signature,
like,
public runRandomly(Activity activity) {
this.activity = activity;
context = activity;
}
also override this method
#Override
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
if (values[0] == 0) {
mDialog.setTitle("Processing...");
}
mDialog.setProgress(values[0]);
}
update the onProgressUpdate(call it) from your doInBackground(String... params) method
EDIT: you can also give a reference of your EditText view in AsyncTask constructor and do update in onProgressUpdate method.
EDIT: use this code..
public class NewClass extends Activity {
/** Called when the activity is first created. */
EditText edt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newclass);
edt=(EditText)findViewById(R.id.ed);
new runRandomly(this,edt).execute();
}
public class runRandomly extends AsyncTask<String, String, String> {
String ranString="";
Activity activity;
EditText edtt;
public runRandomly(Activity activity,EditText edit) {
this.activity = activity;
edtt=edit;
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try{
for(int a = 0; a < 33; a++)
{
Random rn = new Random();
int i = rn.nextInt(256);
ranString = ranString + i + " ";
}
onProgressUpdate();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(String... values) {
// TODO Auto-generated method stub
edtt.setText(""+ranString);
super.onProgressUpdate(values);
}
}
}
Simple, Thanx.
put this line outside of the for loop it will re-generate new object so no need it in loop
Random rn = new Random();
for(int a = 0; a < 33; a++)
{
int i = rn.nextInt(256);
ranString = ranString + i + " ";
}
you need to Handler and Runnable object which call the AsynTask execute method using runRandomly object
like create this object
Handler handler = new Handler();
runRandomly randomly = new runRandomly();
Runnable callRandom = new Runnable(){
public void run(){
//// call the execute method
randomly.execute();
///// here handler call this runnable every 1 sec i.e 1000 delay time
handler.postDelay(callRandom,1000);
}
}
in onBackground generate the number
#Override
protected String doInBackground(String... params) {
String ranString = "";
Random rn = new Random();
for(int a = 0; a < 33; a++)
{
int i = rn.nextInt(256);
ranString = ranString + i + " ";
}
return ranString;
}
this above method will generate the random number string and when it finish this will return that string to the postExecute();
#Override
protected void onProgressUpdate(String values) {
super.onProgressUpdate(values);
if(values!=null & !values.equals(""))
txtMessage.setText(ranString);
}

notifyDataSetChanged not working in android

The list view is not updating data when the notifyDataChanged() method called.
In onCreate() method i initialized the the listview with no data.
ListView videoList = (ListView)findViewById(R.id.videos_list);
videoList.setOnItemClickListener(listener);
listAdapter = new PHVideosListAdapter(PHVideosActivity.this, videos);
videoList.setAdapter(listAdapter);
After this I started fetching list of video using new VideosCategoryFetchTask().execute();
in the post execute method I called
#Override
protected void onPostExecute(Boolean success) {
if(success) {
listAdapter.notifyDataSetChanged();
} else {
//show dialog
}
}
but nothing is displayed on the list. If anybody knew the solution please help...
private class VideosDetailsFetchTask extends AsyncTask<String, Void, Boolean> {
#Override
public void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... params) {
Boolean success = false;
try {
if (params.length >= 0) {
videos = (Videos)videoAPI.videosForCategoryId(params[0],new VideosParser());
success = true;
}
} catch (Exception e) {
// TODO: handle exception
}
return success;
}
#Override
protected void onPostExecute(Boolean success) {
if(success) {
progressBar.setVisibility(View.INVISIBLE);
onFinishVideoFetch();
} else {
//show dialog
}
}
}
here using two Async classes sec one is called on the onPostExecute() of first one..
private void onFinishVideoFetch() {
if(videos != null) {
listAdapter.notifyDataSetChanged();
}
}
I 'm not fetching videos one by one.. here a list of videos is returned....
After getting the list of videos i wanted to refresh the list.
#Override
protected void onProgressUpdate(Videos... values) {
videos = values[0];
//add published object to list which holds
listAdapter.notifyDataSetChanged();
}
I tried this but no luck please help..
this is the adapter class used
public class PHVideosListAdapter extends BaseAdapter{
private Videos videoTitles;
private LayoutInflater inflater;
public PHVideosListAdapter(Context context, Videos videoTitles) {
inflater = LayoutInflater.from(context);
this.videoTitles = videoTitles;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
if(videoTitles != null) {
return videoTitles.size();
}
else {
return 0;
}
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return videoTitles.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
VideoListViewHolder holder = null;
if (convertView == null) {
holder = new VideoListViewHolder();
convertView = inflater.inflate(R.layout.videos_list, null);
holder.videoTitle = (TextView) convertView.findViewById(R.id.video_title);
holder.videoImage = (ImageView) convertView.findViewById(R.id.video_image);
holder.videoDuration = (TextView) convertView.findViewById(R.id.video_duration);
convertView.setTag(holder);
} else {
holder = (VideoListViewHolder)convertView.getTag();
}
holder.videoImage.setImageResource(R.drawable.icon);
holder.videoDuration.setText("00:10");
holder.videoTitle.setText(videoTitles.get(position).getVideoTitle());
return convertView;
}
private class VideoListViewHolder {
ImageView videoImage;
TextView videoTitle;
TextView videoDuration;
}
}
When you first create your PHVideosListAdapter, it is holding a reference to the Videos list that I assume is a member of your Activity. In your doInBackground method, the call to videoAPI.videosForCategoryId is updating the Videos reference in your Activity, but the adapter is still holding the original reference that was passed in to the constructor for PHVideosListAdapter. You need to either recreate the PHVideosListAdapter in onPostExecute or add a set method in PHVideosListAdapter to change the private variable videoTitles.
I ran into the same issue with using the ArrayAdapter provided by Google. You can only set the underlying List in the constructor, so you must recreate the ArrayAdapter or create your own class that allows changing of the underlying data for notifyDataSetChanged to work.
You need to override onProgressUpdate() of AsynTask class
Heres an example of AsyncTask assuming your list is videos which holds Objects of type Video and your extended adapter is VideosAdapter
private class VideosDetailsFetchTask extends AsyncTask<String, Video, Boolean> {
#Override
public void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... params) {
//utilize string you are passing otherwise use Void as first generic param.
Boolean success = false;
try {
if (params.length >= 0) {
Videos videoFetched = (Videos)PrimeraHoraAPI.videosForCategoryId(params[0],new VideosParser());
success = true;
publishProgress(videoFetched);
}
} catch (Exception e) {
// TODO: handle exception
}
return success;
}
#Override
protected void onPostExecute(Boolean success) {
if(success) {
progressBar.setVisibility(View.INVISIBLE);
onFinishVideoFetch();
} else {
//show dialog
}
}
#Override
protected void onProgressUpdate(Video... values) {
videos.add(values[0]);//add published object to list which holds
((VideosAdapter)getListAdapter()).notifyDataSetChanged();
}
}
It's not very good descript anywhere but what you do when u call
listAdapter.notifyDataSetChanged();
u tell your machine "oke, your code is not legit" and now u stop! so basically ur machine has no clue what 2 do next! My solution is:
create a private void setupData()
private void setupData() {
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
final List<Table_Follow> data = db.getAllData(); // from database
HashMap<String,String> item;
for(Table_Data td : data){
item = new HashMap<String,String>();
item.put("name1", td.getName_One());
item.put("name2", td.getName_Two());
item.put("date", td.getDate());
list.add(item);
};
my_data = new SimpleAdapter(this, list, R.layout.my_listview_row, new String[] { "name1","name2", "date" }, new int[] {R.id.lv_line_a, R.id.lv_line_b, R.id.lv_line_c});
listview.setAdapter(my_data);
}
I have a custom layout with 3 textviews (line a > title, line b > subtitle, line c > time see bottom page for xml). So basicly i ll use this private void to tell my machine what 2 do next by using setupData() after calling > notifydatasetchanged() in my main thread
my_data.notifyDataSetChanged();
setupData();
One last thing! I use the android listview id for my listview in my main xml file! Oh and if you have trouble using your 'onItemClickListener' (not giving u the right id, just text me! I faced that problem and solved it pretty shitty but it works :p)
My xml file for my listview:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/lv_line_c"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFFFFF"
android:textSize="15sp" />
<LinearLayout
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/lv_line_a"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#FFFFFF"
android:textSize="24sp"
android:textStyle="bold" />
<TextView
android:id="#+id/lv_line_b"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#FFFFFF"
android:textSize="15sp" />
</LinearLayout>
</RelativeLayout>

Categories

Resources