//testselect.java
package com.example.eleave;
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class TestSelect extends Activity {
Intent i;
Button btn4;
CharSequence[] options;
protected ArrayList<CharSequence> selectedSubjects = new ArrayList<CharSequence>();
boolean[] selections;
String s1;
String sub[]=new String[5];
TextView tv2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.testselect);
i=getIntent();
s1=i.getStringExtra("data1");
tv2=(TextView) findViewById(R.id.textView2);
btn4=(Button) findViewById(R.id.button4);
btn4.setOnClickListener(new ButtonClickHandler());
Bundle bundle = getIntent().getExtras();
String username = bundle.getString("username");
String reason = bundle.getString("reason");
String sem = bundle.getString("sem");
String from = bundle.getString("from");
String to = bundle.getString("to");
AsyncTask<String,Void,String> t1=new LeaveTask(TestSelect.this).execute(username,sem,reason,from,to);
try{
String result=t1.get();
Toast.makeText(getBaseContext(), result,Toast.LENGTH_LONG).show();
}catch(Exception e)
{
}
}
public class ButtonClickHandler implements View.OnClickListener {
public void onClick( View view ) {
if(s1.equals("III"))
{
options=new CharSequence[]{"DSPD","CAO","BDP"};
selections = new boolean[ options.length ];
}
else if(s1.equals("IV"))
{
options=new CharSequence[] {"TOFCS","OOP","OS"};
selections = new boolean[ options.length ];
}
else if(s1.equals("V"))
{
options=new CharSequence[] {"MI","CG","SP"};
selections = new boolean[ options.length ];
}
else
{
options=new CharSequence[] {"DAA","DBMS","ICWS"};
selections = new boolean[ options.length ];
}
showDialog( 0 );
/* do whatever you want with the checked item */
}
}
#Override
protected Dialog onCreateDialog( int id )
{
return
new AlertDialog.Builder( this )
.setTitle( "SUBJECTS" )
.setMultiChoiceItems( options, selections, new DialogSelectionClickHandler() )
.setPositiveButton( "OK", new DialogButtonClickHandler() )
.create();
}
public class DialogSelectionClickHandler implements DialogInterface.OnMultiChoiceClickListener
{
public void onClick( DialogInterface dialog, int clicked, boolean selected )
{
Log.i( "ME", options[ clicked ] + " selected: " + selected );
if(selected)
{
selectedSubjects.add(options[clicked]);
}
else
{
selectedSubjects.remove(options[clicked]);
}
}
}
public class DialogButtonClickHandler implements DialogInterface.OnClickListener
{
private final String NULL = null;
boolean[] checkedSubjects = new boolean[options.length];
int count = options.length;
public void onClick( DialogInterface dialog, int clicked, boolean isChecked)
{
switch( clicked )
{
case DialogInterface.BUTTON_POSITIVE:
printSelectedSubjects();
break;
}
}
private void printSelectedSubjects() {
// TODO Auto-generated method stub
for( int i = 0; i < options.length; i++ ){
Log.i( "ME", options[ i ] + " selected: " + selections[i] );
}
for(int i = 0; i < count; i++)
checkedSubjects[i] = selectedSubjects.contains(options[i]);
StringBuilder stringBuilder = new StringBuilder();
for(CharSequence subject : selectedSubjects)
stringBuilder.append(subject + ",");
tv2=(TextView) findViewById(R.id.textView2);
tv2.setText(stringBuilder.toString());
}
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
}
}
I am passing value of s1 that is semester from some other activity and each semester has set of subjects I need to select more than one subject and extract all the values as string but I am unable to do so.Please help
I advise you to look at this code sample: here
The sample is actually quite similar to what you are trying to do...
You don't need to keep track of the checked items yourself. You can just use the boolean-array you passed to the dialog. "selections" in your case.
Related
I am new to Android development, I am working on a App and I want to convert my below mentioned code to AnsyncTask. Because it is showing me Run-time error that I am doing too much work on UI thread. Please help me to convert it to AnsyncTask.
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class PlayActivity extends AppCompatActivity {
GridView gridview;
TextView textView;
TextView result;
TextView remainingChance;
Button giveup;
Button goback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
textView = (TextView) findViewById(R.id.blanks);
result = (TextView) findViewById(R.id.result);
remainingChance = (TextView) findViewById(R.id.remainingChance);
giveup = (Button) findViewById(R.id.giveup);
goback = (Button) findViewById(R.id.goback);
goback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent goBack = new Intent(PlayActivity.this, MainActivity.class);
startActivity(goBack);
}
});
String dash = "";
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String easyArray[] = bundle.getStringArray("easy");
final String randomStr = easyArray[new Random().nextInt(easyArray.length)]; // Getting a random string from Array
giveup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(randomStr); // By clicking on Give up button, it displays the actual word & a message Go Back and try again
remainingChance.setText("Go Back and try again");
}
});
final Integer strLength = randomStr.length();
// Creating string with question mark with 2nd and 5th character only
for(int i=1; i<=strLength; i++){
if(i == 2){
dash = dash+Character.toString(randomStr.charAt(1));
} else if (i == 5){
dash = dash+ Character.toString(randomStr.charAt(4));
} else {
dash = dash + "?";
}
}
final String displayVal = dash;
textView.setText(displayVal); // Displaying string with question mark with 2nd and 5th character only
gridview = (GridView) findViewById(R.id.gridview);
final String[] mAlphabets = new String[]{"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
final ArrayList<String> array_list = new ArrayList<String>(Arrays.asList(mAlphabets));
final ArrayAdapter arrayAdapter = new ArrayAdapter (getApplicationContext(),android.R.layout.simple_list_item_1,array_list);
gridview.setNumColumns(8);
gridview.setBackgroundColor(Color.BLUE);
gridview.setGravity(Gravity.CENTER);
gridview.setAdapter(arrayAdapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
String finalDisplayVal = displayVal;
int count = 0;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final ProgressDialog mProgressDialog = new ProgressDialog(PlayActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading...");
// Set progressdialog message
mProgressDialog.setMessage("Checkinggg...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
long delayInMillis = 1000;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
mProgressDialog.dismiss();
}
}, delayInMillis);
String itemValue = (String) gridview.getItemAtPosition(position);
array_list.remove(position); // Removing character from 26 alphabets which is clicked by user
arrayAdapter.notifyDataSetChanged(); // Reset gridview
if(randomStr.contains(itemValue)){ // If selected alphabets exists in string
for(int k=0; k<strLength; k++){
if(Character.toString(randomStr.charAt(k)).equalsIgnoreCase(itemValue)){
int charPos = randomStr.indexOf(itemValue);
while(charPos >= 0){
finalDisplayVal = replaceCharAt(finalDisplayVal, charPos, itemValue);
textView.setText(finalDisplayVal);
charPos = randomStr.indexOf(itemValue, charPos + 1);
}
}
}
checkWinCount(); // Checking if User Wins
} else {
count++;
int remVal = 4-count;
remainingChance.setText("Not Exist, You have " + remVal + " chance(s) left.");
}
checkLoseCount(); // Checking if User Lose
}
public String replaceCharAt(String s, int pos, String c) {
return s.substring(0, pos) + c + s.substring(pos + 1);
}
public void checkLoseCount() {
if(count > 3) {
Toast.makeText(PlayActivity.this, "You Loose, Value is: "+randomStr, Toast.LENGTH_LONG).show();
Intent goBack = new Intent(PlayActivity.this, MainActivity.class);
startActivity(goBack);
}
}
public void checkWinCount(){
if(randomStr.equalsIgnoreCase(finalDisplayVal)){
Toast.makeText(PlayActivity.this, "Hurray!!! You WIN... It's "+randomStr, Toast.LENGTH_LONG).show();
Intent goBack = new Intent(PlayActivity.this, MainActivity.class);
startActivity(goBack);
}
}
});
}
}
AsyncTask Code;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import android.os.AsyncTask;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class PlayActivity1 extends AppCompatActivity {
GridView gridview;
TextView textView;
TextView result;
TextView remainingChance;
Button giveup;
Button goback;
int count = 0;
String randomStr;
String finalDisplayVal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
textView = (TextView) findViewById(R.id.blanks);
result = (TextView) findViewById(R.id.result);
remainingChance = (TextView) findViewById(R.id.remainingChance);
giveup = (Button) findViewById(R.id.giveup);
goback = (Button) findViewById(R.id.goback);
goback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent goBack = new Intent(PlayActivity1.this, MainActivity.class);
startActivity(goBack);
}
});
String dash = "";
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String easyArray[] = bundle.getStringArray("easy");
final String randomStr = easyArray[new Random().nextInt(easyArray.length)]; // Getting a random string from Array
giveup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(randomStr); // By clicking on Give up button, it displays the actual word & a message Go Back and try again
remainingChance.setText("Go Back and try again");
}
});
final Integer strLength = randomStr.length();
// Creating string with question mark with 2nd and 5th character only
for (int i = 1; i <= strLength; i++) {
if (i == 2) {
dash = dash + Character.toString(randomStr.charAt(1));
} else if (i == 5) {
dash = dash + Character.toString(randomStr.charAt(4));
} else {
dash = dash + "?";
}
}
final String displayVal = dash;
textView.setText(displayVal); // Displaying string with question mark with 2nd and 5th character only
gridview = (GridView) findViewById(R.id.gridview);
final String[] mAlphabets = new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
final ArrayList<String> array_list = new ArrayList<String>(Arrays.asList(mAlphabets));
final ArrayAdapter arrayAdapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, array_list);
gridview.setNumColumns(8);
gridview.setBackgroundColor(Color.BLUE);
gridview.setGravity(Gravity.CENTER);
gridview.setAdapter(arrayAdapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
AsyncTaskRunner runner = new AsyncTaskRunner();
String finalDisplayVal = displayVal;
runner.execute(finalDisplayVal);
String itemValue = (String) gridview.getItemAtPosition(position);
array_list.remove(position); // Removing character from 26 alphabets which is clicked by user
arrayAdapter.notifyDataSetChanged(); // Reset gridview
if (randomStr.contains(itemValue)) { // If selected alphabets exists in string
for (int k = 0; k < strLength; k++) {
if (Character.toString(randomStr.charAt(k)).equalsIgnoreCase(itemValue)) {
int charPos = randomStr.indexOf(itemValue);
while (charPos >= 0) {
finalDisplayVal = replaceCharAt(finalDisplayVal, charPos, itemValue);
textView.setText(finalDisplayVal);
charPos = randomStr.indexOf(itemValue, charPos + 1);
}
}
}
checkWinCount(); // Checking if User Wins
} else {
count++;
int remVal = 4 - count;
remainingChance.setText("Not Exist, You have " + remVal + " chance(s) left.");
}
checkLoseCount(); // Checking if User Lose
}
});
}
public String replaceCharAt(String s, int pos, String c) {
return s.substring(0, pos) + c + s.substring(pos + 1);
}
public void checkLoseCount() {
if (count > 3) {
Toast.makeText(PlayActivity1.this, "You Loose, Value is: " + randomStr, Toast.LENGTH_LONG).show();
Intent goBack = new Intent(PlayActivity1.this, MainActivity.class);
startActivity(goBack);
}
}
public void checkWinCount() {
if (randomStr.equalsIgnoreCase(finalDisplayVal)) {
Toast.makeText(PlayActivity1.this, "Hurray!!! You WIN... It's " + randomStr, Toast.LENGTH_LONG).show();
Intent goBack = new Intent(PlayActivity1.this, MainActivity.class);
startActivity(goBack);
}
}
private class AsyncTaskRunner extends AsyncTask<String, String, ProgressDialog> {
#Override
protected ProgressDialog doInBackground(String... params) {
final ProgressDialog mProgressDialog = new ProgressDialog(PlayActivity1.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading...");
// Set progressdialog message
mProgressDialog.setMessage("Checkinggg...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
try {
long delayInMillis = 1000;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
mProgressDialog.dismiss();
}
}, delayInMillis);
}catch (Exception e){
e.printStackTrace();
}
return mProgressDialog;
}
}
}
I want to get HashMap which is being passed through Bundle from a AsyncTask. But I am getting NullPointerException.
Flow is like below...
FragmentMainActivity -> TableScreenSectionwiseActivity -> GetSectionsAsync
HashMap is passed from GetSectionsAsync to TableScreenSectionwiseActivity through Bundle.
Note: FragmentMainActivity is FragmentActivity.TableScreenSectionwiseActivity is Fragment.GetSectionsAsync is a AsyncTask.
What I have tried, is like below.
Error I getting...
Error Image
TableScreenSectionwiseActivity.java
package com.malaka.ui;
import java.util.ArrayList;
import java.util.HashMap;
import adapters.table_section_adapter;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.malaka.R;
import com.malaka.helper.ActionItem;
import com.malaka.helper.GetSectionsGetterSetter;
import com.malaka.helper.Logout;
import com.malaka.helper.PopupWindows;
import com.malaka.helper.QuickAction;
import com.malaka.helper.QuickActionLocation;
import com.malaka.helper.ReplaceFragment;
import com.malaka.helper.async.GetSectionsAsync;
import com.malaka.helper.async.TableStatusAsync;
import com.malaka.utils.PreferenceUtils;
public class TableScreenSectionwiseActivity extends Fragment implements
OnItemClickListener {
final static String TAG = "TableScreenSectionwiseActivity";
private static final int ID_TABLE = 1;
private static final int ID_TASK = 2;
private static final int ID_MANAGER = 3;
private static final int ID_RECIPE = 4;
private static final int ID_INSTRUCTION = 5;
private static final int ID_SEARCH = 6;
private static final int ID_HELP = 7;
private static final int ID_SETTING = 8;
private static final int ID_LOGOUT = 9;
private static final int ID_KP = 10;
private static final int ID_BANER = 20;
private static final int ID_CITY = 30;
String[] values = new String[] { "1", "2" };
public static FragmentActivity activity;
RelativeLayout rl;
static PreferenceUtils pref;
QuickAction quickAction;
QuickActionLocation quickActionLocation;
HashMap<String, ArrayList<String>> map1;
ArrayList<String> ids, names;
ListView section_list;
TextView version, malaka;
ImageView refresh;
Animation rotation;
private TextView mDropdownTitle;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.table_screen_sectionwise,
container, false);
init(view);
return view;
}
private void init(View view) {
activity = getActivity();
pref = new PreferenceUtils(getActivity());
malaka = (TextView) view
.findViewById(R.id.txt_malaka_title_table_sectionwise);
malaka.setText(pref.getLocation());
if (!pref.getSectionStatus()) {
GetSectionsAsync getSectionsAsync = new GetSectionsAsync(
getActivity());
HashMap<String, String> map = new HashMap<String, String>();
map.put("Location_Name", pref.getLocation());
getSectionsAsync.execute(map);
}
Bundle bundle = new Bundle();
Log.e("Bundle Size: ", bundle.size() + "");
map1 = (HashMap<String, ArrayList<String>>) getArguments()
.getSerializable("SECTIONS_HASHMAP");
GetSectionsGetterSetter.setData(map1);
ids = map1.get("ID_LIST");
names = map1.get("NAME_LIST");
for (int i = 0; i < names.size(); i++) {
Log.e("Names: ", names.get(i));
}
section_list = (ListView) view
.findViewById(R.id.section_name_list_view);
table_section_adapter adapter = new table_section_adapter(
activity.getApplicationContext(), values);
section_list.setAdapter(adapter);
section_list.setOnItemClickListener(this);
rl = (RelativeLayout) view.findViewById(R.id.ll_location_sectionwise);
if (pref.getUserRole()) {
rl.setVisibility(View.VISIBLE);
} else {
rl.setVisibility(View.GONE);
}
rl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
quickActionLocation.show(arg0);
}
});
version = (TextView) view.findViewById(R.id.table_version_sectionwise);
version.setText(pref.getVersion());
rotation = AnimationUtils.loadAnimation(getActivity(),
R.anim.refresh_dialog);
refresh = (ImageView) view
.findViewById(R.id.img_refresh_table_sectionwise);
refresh.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
refresh.startAnimation(rotation);
TableStatusAsync Async = new TableStatusAsync(getActivity());
HashMap<String, String> map = new HashMap<String, String>();
map.put("UserId", pref.getUserId());
map.put("SectionId", "0");
map.put("Location", pref.getLocation());
Async.execute(map);
}
});
ActionItem tableItem = new ActionItem(ID_TABLE, "Table Status");
ActionItem taskItem = new ActionItem(ID_TASK, "My Tasks");
ActionItem managerItem = new ActionItem(ID_MANAGER, "Manager");
ActionItem recipeItem = new ActionItem(ID_RECIPE, "Recipes");
ActionItem instItem = new ActionItem(ID_INSTRUCTION, "Instructions");
ActionItem searchItem = new ActionItem(ID_SEARCH, "Search");
ActionItem helpItem = new ActionItem(ID_HELP, "Help");
ActionItem settingItem = new ActionItem(ID_SETTING, "Settings");
ActionItem logoutItem = new ActionItem(ID_LOGOUT, "Logout");
ActionItem kpItem = new ActionItem(ID_KP, "Koregaon Park");
ActionItem cityItem = new ActionItem(ID_CITY, "Phoneix Market");
ActionItem banerItem = new ActionItem(ID_BANER, "Baner");
quickActionLocation = new QuickActionLocation(getActivity(),
QuickActionLocation.VERTICAL);
quickActionLocation.addActionItem(kpItem, Color.WHITE);
quickActionLocation.addActionItem(cityItem, Color.WHITE);
quickActionLocation.addActionItem(banerItem, Color.WHITE);
// use setSticky(true) to disable QuickAction dialog being dismissed
// after an item is clicked
// tableItem.setSticky(true);
// create QuickAction. Use QuickAction.VERTICAL or
// QuickAction.HORIZONTAL param to define layout
// orientation
quickAction = new QuickAction(getActivity(), QuickAction.VERTICAL);
// add action items into QuickAction
quickAction.addActionItem(tableItem, Color.WHITE);
quickAction.addActionItem(taskItem, Color.parseColor("#F2A523"));
if (pref.getUserRole()) {
quickAction.addActionItem(managerItem, Color.parseColor("#F2A523"));
}
if (pref.getRecipeScreenStatus()) {
quickAction.addActionItem(recipeItem, Color.parseColor("#F2A523"));
}
quickAction.addActionItem(instItem, Color.parseColor("#F2A523"));
quickAction.addActionItem(searchItem, Color.parseColor("#F2A523"));
quickAction.addActionItem(helpItem, Color.parseColor("#F2A523"));
quickAction.addActionItem(settingItem, Color.parseColor("#F2A523"));
quickAction.addActionItem(logoutItem, Color.parseColor("#F2A523"));
// Set listener for action item clicked
quickAction
.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {
#Override
public void onItemClick(QuickAction source, int pos,
int actionId) {
ActionItem actionItem = quickAction.getActionItem(pos);
quickAction.dismiss();
// here we can filter which action item was clicked with
// pos or actionId parameter
if (actionId == ID_TABLE) {
closeDropdown();
} else if (actionId == ID_TASK) {
closeDropdown();
ReplaceFragment.getReplaceFragment(getActivity(),
new TaskLeadingActivity(), "left");
} else if (actionId == ID_MANAGER) {
closeDropdown();
ReplaceFragment.getReplaceFragment(getActivity(),
new ManagerPageActivity(), "left");
} else if (actionId == ID_RECIPE) {
closeDropdown();
ReplaceFragment.getReplaceFragment(getActivity(),
new ReceipiesScreenActivity(), "left");
} else if (actionId == ID_INSTRUCTION) {
closeDropdown();
ReplaceFragment.getReplaceFragment(getActivity(),
new InstructionActivity(), "left");
} else if (actionId == ID_SEARCH) {
closeDropdown();
} else if (actionId == ID_HELP) {
closeDropdown();
} else if (actionId == ID_SETTING) {
closeDropdown();
ReplaceFragment.getReplaceFragment(getActivity(),
new SettingScreenActivity(), "left");
} else if (actionId == ID_LOGOUT) {
closeDropdown();
Logout logout = new Logout(getActivity());
}
}
});
// set listnener for on dismiss event, this listener will be called only
// if QuickAction dialog was dismissed
// by clicking the area outside the dialog.
quickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
#Override
public void onDismiss() {
// Toast.makeText(getActivity(), "Dismissed",
// Toast.LENGTH_SHORT).show();
closeDropdown();
}
});
// Set listener for action item clicked
quickActionLocation
.setOnActionItemClickListener(new QuickActionLocation.OnActionItemClickListener() {
#Override
public void onItemClick(QuickActionLocation source,
int pos, int actionId) {
ActionItem actionItem = quickActionLocation
.getActionItem(pos);
quickActionLocation.dismiss();
// here we can filter which action item was clicked with
// pos or actionId parameter
if (actionId == ID_KP) {
getTableStatus("Koregaon Park");
} else if (actionId == ID_CITY) {
getTableStatus("Phoneix Market City");
} else if (actionId == ID_BANER) {
getTableStatus("Baner");
}
}
});
mDropdownTitle = ((TextView) view
.findViewById(R.id.dropdown_textview_table_sectionwise));
mDropdownTitle.setText(pref.getUserNameToGetManagerPage()
.substring(0, 1).toUpperCase()
+ pref.getUserNameToGetManagerPage().substring(1).toLowerCase()
+ " ");
final TextView dropDownTextView = (TextView) view
.findViewById(R.id.dropdown_textview_table_sectionwise);
dropDownTextView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (PopupWindows.mWindow.isShowing()) {
closeDropdown();
} else {
openDropdown();
}
quickAction.show(v);
}
});
}
public void getTableStatus(String location) {
pref.setLocation(location);
Log.e(TAG, "location : " + pref.getLocation());
TableStatusAsync Async = new TableStatusAsync(getActivity());
HashMap<String, String> map = new HashMap<String, String>();
map.put("UserId", pref.getUserId());
map.put("SectionId", "0");
map.put("Location", pref.getLocation());
Async.execute(map);
}
private void openDropdown() {
mDropdownTitle.setCompoundDrawablesWithIntrinsicBounds(0, 0,
R.drawable.arrow_up, 0);
}
private void closeDropdown() {
mDropdownTitle.setCompoundDrawablesWithIntrinsicBounds(0, 0,
R.drawable.arrow_down, 0);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(activity, "Clicked" + position, Toast.LENGTH_SHORT)
.show();
}
}
GetSectionsAsync.java
package com.malaka.helper.async;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.malaka.helper.AsyncAttributes;
import com.malaka.helper.ReplaceFragment;
import com.malaka.helper.TableStatusXmlParser;
import com.malaka.ui.CustomerDetailsActivity;
import com.malaka.ui.TableScreenSectionwiseActivity;
import com.malaka.utils.CommanUtils;
import com.malaka.utils.NetworkUtils;
import com.malaka.utils.PreferenceUtils;
public class GetSectionsAsync extends
AsyncTask<Map<String, String>, Void, Void> {
final static String TAG = "GetSectionsAsync";
FragmentActivity context;
String xml;
HashMap<String, ArrayList<String>> details;
PreferenceUtils pref;
int response;
boolean isConnected;
public GetSectionsAsync(FragmentActivity context) {
this.context = context;
pref = new PreferenceUtils(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
CommanUtils.getDialogShow(context, "Please Wait...");
}
#Override
protected Void doInBackground(Map<String, String>... params) {
if (NetworkUtils.isConnectedToInternet(context)) {
isConnected = true;
HashMap<String, String> map = (HashMap<String, String>) params[0];
SoapObject request = new SoapObject(
AsyncAttributes.GetSecNAMESPACE,
AsyncAttributes.GetSecMETHOD_NAME);
Iterator<String> iterator = map.keySet().iterator();
PropertyInfo pi = new PropertyInfo();
pi.setName("RLocation");
pi.setValue(map.get("Location_Name"));
pi.setType(String.class);
request.addProperty(pi);
while (iterator.hasNext()) {
String key = iterator.next();
request.addProperty(key, map.get(key));
Log.e(TAG, "user id key: " + key + " value: " + map.get(key));
}
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(
AsyncAttributes.GetSecURL);
try {
androidHttpTransport.call(AsyncAttributes.GetSecSOAP_ACTION,
envelope);
SoapObject result = (SoapObject) envelope.bodyIn;
if (result
.toString()
.equals("GetSectionsForLocationResponse{GetSectionsForLocationResult=Failur; }")) {
String xmltemp = String.valueOf(result).split("=")[1];
xml = xmltemp.split(";")[0];
} else {
String xmltemp = "<NewDataSet>\n"
+ String.valueOf(result).split("<NewDataSet>")[1];
xml = xmltemp.split("</NewDataSet>")[0] + "</NewDataSet>";
}
} catch (Exception e) {
e.printStackTrace();
}
if (xml == null) {
response = 1;
Log.e(TAG, "xml null");
} else if (xml.equals("No Table available")) {
response = 2;
} else {
response = 2;
Log.e(TAG, "Task 1 result " + xml);
details = TableStatusXmlParser.getSectionsXml(xml, context);
}
} else {
isConnected = false;
}
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
CommanUtils.getDialogDismiss();
if (!isConnected) {
CommanUtils.showAlertDialog("Internet Is Required", context);
} else if (response == 1) {
CommanUtils.getToast("Server Error", context);
}
if (response == 2) {
pref.setSectionStatus(true);
goAhead();
}
}
private void goAhead() {
Bundle bundle = new Bundle();
bundle.putSerializable("SECTIONS_HASHMAP", details);
Fragment fragment = new TableScreenSectionwiseActivity();
fragment.setArguments(bundle);
ReplaceFragment.getReplaceFragment(context, fragment, "");
}
}
If you guys want FragmentMainActivity code. I can put it. But I dont think so it is required. Thanks in advance.
At the end I have achieved it through INTERFACE.
Just do like below...
Make interface in GetSectionsAsync.java named FragmentInterfaceCallBack and declare a method named onTaskCompleted().
Now define a method in GetSectionsAsync.java named setFragmentInterfaceCallBack which will set the interface's object while calling from TableScreenSectionwiseActivity.java.
Now in onPostExecute method write below code....interfaceCallBack.onTaskCompleted(details); details is a data received from web service.
Go to TableScreenSectionwiseActivity.java and implements FragmentInterfaceCallBack, define it's onTaskCompleted() method and add below code to TableScreenSectionwiseActivity.java where you are calling AsyncTask getSectionsAsync.setFragmentInterfaceCallBack(this); where getSectionsAsync is a object of GetSectionsAsync.java.
In onTaskCompleted() method you get your desire data.
I have made below changes in my both files.
GetSectionsAsync.java
Making interface and defining setFragmentInterfaceCallBack() method....
private FragmentInterfaceCallBack interfaceCallBack;
public interface FragmentInterfaceCallBack {
public void onTaskCompleted(HashMap<String, ArrayList<String>> map);
}
public void setFragmentInterfaceCallBack(
FragmentInterfaceCallBack _interfaceCallBack) {
this.interfaceCallBack = _interfaceCallBack;
}
In onPostExecute method....
protected void onPostExecute(Void result) {
super.onPostExecute(result);
CommanUtils.getDialogDismiss();
if (!isConnected) {
CommanUtils.showAlertDialog("Internet Is Required", context);
} else if (response == 1) {
CommanUtils.getToast("Server Error", context);
}
if (response == 2) {
pref.setSectionStatus1(true);
// goAhead();
}
interfaceCallBack.onTaskCompleted(details);
}
TableScreenSectionwiseActivity.java
Implementing interface....
public class TableScreenSectionwiseActivity extends Fragment implements OnItemClickListener, FragmentInterfaceCallBack {
Calling AsyncTask....
if (!pref.getSectionStatus1()) {
Log.e("Once Again in TableScreenSectionwiseActivity: ", "hmm....");
GetSectionsAsync getSectionsAsync = new GetSectionsAsync(
getActivity());
getSectionsAsync.setFragmentInterfaceCallBack(this);
HashMap<String, String> map = new HashMap<String, String>();
map.put("Location_Name", pref.getLocation());
getSectionsAsync.execute(map);
}
Defining interface's method....
#Override
public void onTaskCompleted(HashMap<String, ArrayList<String>> hashMap) {
ids = hashMap.get("ID_LIST");
names = hashMap.get("NAME_LIST");
table_section_adapter adapter = new table_section_adapter(
activity.getApplicationContext(), names, ids);
section_list.setAdapter(adapter);
section_list.setOnItemClickListener(this);
}
That's it. Hope this will help someone..
Map<String, String> map = ((Bundle)appRestrictions.get(key)).keySet().stream().collect(Collectors.toMap(x -> x, x -> bundle.get(x).toString()));
JSONObject jsonNested = new JSONObject(map);
i have already searched high and low on the net.
tried several tips and tutorials but none is really working for me.
What i am trying to do is using a multiple choicelist to delete more than 1 entry in my list.
everything is working, and the list is set to multiplechoice in the xml, but when trying to update my custom list i can't seem to fix that recycling.
I am using a resourcecursoradapter, no idea if that is the problem or not, but i'm at a loss right now, so if any body could help me that would be great.
Now for the code of my Activity.
package com.ShaHar91.ivlibrary;
import java.io.IOException;
import java.io.InputStream;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.SQLException;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
#SuppressWarnings("deprecation")
public class DeleteMultiPoke extends ListActivity {
public static final String ROW_ID = "row_id"; // Intent extra key
private long rowID;
MyAdapter mListAdapter;
Menu menu;
MenuItem delete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
DatabaseConnector myDbHelper = new DatabaseConnector(
DeleteMultiPoke.this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
DatabaseConnector.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
Cursor myCur = null;
myCur = myDbHelper.getAllPokes();
mListAdapter = new MyAdapter(DeleteMultiPoke.this, myCur);
setListAdapter(mListAdapter);
}
private class MyAdapter extends ResourceCursorAdapter {
public MyAdapter(Context context, Cursor cur) {
super(context, R.layout.poke_list_remove_item, cur);
}
#Override
public View newView(Context context, Cursor cur, ViewGroup parent) {
LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
return li.inflate(R.layout.poke_list_remove_item, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cur) {
TextView pokeTv = (TextView) view.findViewById(R.id.pokeTv);
TextView genderTv = (TextView) view.findViewById(R.id.genderTv);
RadioButton hpRb = (RadioButton) view.findViewById(R.id.hpRb);
RadioButton attRb = (RadioButton) view.findViewById(R.id.attRb);
RadioButton defRb = (RadioButton) view.findViewById(R.id.defRb);
RadioButton spAttRb = (RadioButton) view.findViewById(R.id.spAttRb);
RadioButton spDefRb = (RadioButton) view.findViewById(R.id.spDefRb);
RadioButton speedRb = (RadioButton) view.findViewById(R.id.speedRb);
ImageView pokeSprite = (ImageView) view
.findViewById(R.id.pokeSpriteIV);
pokeTv.setText(cur.getString(cur.getColumnIndex("name")));
genderTv.setText(cur.getString(cur.getColumnIndex("gender")));
hpRb.setChecked((cur.getInt(cur.getColumnIndex("hp")) == 0 ? false
: true));
attRb.setChecked((cur.getInt(cur.getColumnIndex("att")) == 0 ? false
: true));
defRb.setChecked((cur.getInt(cur.getColumnIndex("def")) == 0 ? false
: true));
spAttRb.setChecked((cur.getInt(cur.getColumnIndex("sp_att")) == 0 ? false
: true));
spDefRb.setChecked((cur.getInt(cur.getColumnIndex("sp_def")) == 0 ? false
: true));
speedRb.setChecked((cur.getInt(cur.getColumnIndex("speed")) == 0 ? false
: true));
AssetManager assetManager = getAssets();
int imageIndex = cur.getColumnIndex("nat_dex");
try {
InputStream ims = assetManager.open("pokes/"
+ cur.getString(imageIndex) + ".gif");
Drawable d = Drawable.createFromStream(ims, null);
pokeSprite.setImageDrawable(d);
} catch (IOException ex) {
return;
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.poke_menu_remove, menu);
delete = menu.findItem(R.id.deletepokes);
delete.setEnabled(false);
delete.setVisible(false);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.canceldeleting:
finish();
return true;
case R.id.deletepokes:
// create a new AlertDialog Builder
AlertDialog.Builder builder = new AlertDialog.Builder(
DeleteMultiPoke.this);
builder.setTitle(R.string.confirmTitle); // title bar string
builder.setMessage(R.string.confirmMessage); // message to display
// provide an OK button that simply dismisses the dialog
builder.setPositiveButton(R.string.button_delete,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int button) {
final DatabaseConnector databaseConnector = new DatabaseConnector(
DeleteMultiPoke.this);
ListView listView = (ListView) findViewById(android.R.id.list);
SparseBooleanArray checked = listView
.getCheckedItemPositions();
for (int i = checked.size() - 1; i >= 0; i--) {
final int position = checked.keyAt(i);
if (checked.valueAt(i)) {
AsyncTask<Long, Object, Object> deleteTask = new AsyncTask<Long, Object, Object>() {
#Override
protected Object doInBackground(
Long... params) {
databaseConnector.deletePoke(mListAdapter
.getItemId(position));
return null;
}
#Override
protected void onPostExecute(
Object result) {
finish(); // return to the
// BookLibrary Activity
}
};
// delete the AsyncTask to delete book at
// rowID
deleteTask.execute(new Long[] { rowID });
}
}
} // end method onClick
});
builder.setNegativeButton(R.string.button_cancel, null);
builder.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onResume() {
super.onResume();
mListAdapter.getCursor().requery();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String selected = "";
int cntChoice = l.getCount();
SparseBooleanArray sparseBooleanArray = l.getCheckedItemPositions();
for (int i = 0; i < cntChoice; i++) {
if (sparseBooleanArray.get(i)) {
selected += l.getItemAtPosition(i).toString() + "\n";
}
}
Toast.makeText(DeleteMultiPoke.this,
selected,
Toast.LENGTH_LONG).show();
if (l.getCheckedItemCount() == 0) {
delete.setEnabled(false);
delete.setVisible(false);
} else {
delete.setEnabled(true);
delete.setVisible(true);
}
}
Ty in advance,
Christiano Bolla
You should notify the list that the underlying data source has changed by calling notifyDataSetChanged() on your list adapter after deleting any item.
It didn't showing up any error. however when I run my application, there is no result appear from my listView. I think,the mistake is because of i didn't use the correct way doing switch case statement. here is my code.
QuickSearch.java
package com.example.awesome;
import java.io.IOException;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.SQLException;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class QuickSearch extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
//-------------------------------------------------------------------------
// Initiate database data
initiateDb();
//---------------------------------------------------------------------------
// Declaration of view
final Button qsfaculty, qscollege;
super.onCreate(savedInstanceState);
setContentView(R.layout.quick_search);
//---------------------------------------------------------------------------
// Get reference
qsfaculty = (Button) this.findViewById(R.id.button1);
qsfaculty.setOnClickListener(this);
qscollege = (Button) this.findViewById(R.id.button2);
qscollege.setOnClickListener(this);
}
public void onClick(View v) {
char ch = 0;
View qsfaculty = null;
View qscollege = null;
if(v == qsfaculty){
ch = 'a';
}
else if (v == qscollege)
{ch = 'b';}
Intent i = new Intent(this,SearchLocation.class);
i.putExtra("value",ch);
startActivity(i);
}
//---------------------------------------------------------------------------
// Initiate database data
public void initiateDb() {
DatabaseHandler myDbHandler = new DatabaseHandler(this);
try {
myDbHandler.createDataBase();
}
catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHandler.openDataBase();
}
catch(SQLException sqle) {
throw sqle;
}
Log.d("Initiate", "UKM Location Count: " + myDbHandler.getUkmLocationCount());
myDbHandler.close();
}
//------------------------------------------------------------------------------
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.quick_search, menu);
return true;
}
}
SearchLocation.java
package com.example.awesome;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class SearchLocation extends ListActivity {
//------------------------------------------------------------------
// Declaration
public static UkmLocation selectedPOI = null;
final DatabaseHandler db = new DatabaseHandler(this);
private EditText filterText = null;
ArrayAdapter<String> adapter = null;
final ArrayList<String> results = new ArrayList<String>();
final ArrayList<String> results_id = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_location);
final Intent c = new Intent(SearchLocation.this, LocationDetail.class);
//------------------------------------------------------------------
// Link editText to layout item
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
//------------------------------------------------------------------
// Reading Poi
Log.d("Reading", "Reading all Kategori ..");
int value = 0;
switch(value) {
case 'a' :
List<UkmLocation> faculty = db.getCategoryFaculty();
for(UkmLocation k : faculty) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
case 'b' :
List<UkmLocation> college = db.getCategoryCollege();
for(UkmLocation k : college) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
}
//------------------------------------------------------------------
// Set list arrayAdapter to adapter
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.textView1,results);
setListAdapter(adapter);
//------------------------------------------------------------------
// Set ListView from ListActivity
ListView lv = getListView();
lv.setTextFilterEnabled(true);
//------------------------------------------------------------------
// Set click event from listView
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
Log.d("test", "position:" + position);
Log.d("test", "actualname:" + db.getUkmLocationByName(adapter.getItem(position)).getName());
// String poiID = results_id.get(position);
String poiID = db.getUkmLocationByName(adapter.getItem(position)).getID();
setSelectedPoi(poiID);
startActivity(c);
}
});
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
}
};
#Override
protected void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
public UkmLocation getSelectedPoi() {
return selectedPOI;
}
public void setSelectedPoi(String poiID) {
selectedPOI = db.getUkmLocation(poiID);
Log.d("test2", "_id:" + db.getUkmLocation(poiID).getID());
Log.d("test2", "Name:" + db.getUkmLocation(poiID).getName());
// Closing db
db.close();
}
}
i think,the if else statement inside QuickSearch.java is already correct. the problem at the switch case statement at SearchLocation.java
please help me solve this.
int value = 0;
switch(value) {
You are setting the value over which you switch to 0 so it is equivalent to doing switch(0) {...
Find out what that value is supposed to be and initialise it properly.
Also, value is of type int but your switch uses chars ('a', 'b'), so you need to either have value be a char and initialise it properly or have it be an int, initialise it properly and change your switch cases to use ints.
First you do int value = 0; so value is 0. So it is not 'a' nor 'b'.
You have to get the value from the intent as you put it in extras. i.putExtra("value",ch);
something like
char value;
Bundle extras = getIntent().getExtras();
if (extras != null) {
value = extras.getIntgetChar("value");
}
here, i already solve my problem..
QuickSearch.java
public void onClick(View v) {
int ch = 0;
/*View qsfaculty = null;
View qscollege = null;*/
if(v == qsfaculty){
ch = '1';
}
else if (v == qscollege)
{ch = '2';}
Intent i = new Intent(this,SearchLocation.class);
i.putExtra("value",ch);
startActivity(i);
}
SearchLocation.java
Bundle extras = getIntent().getExtras();
int value = extras.getInt("value");
switch(value) {
case '1' :
List<UkmLocation> faculty = db.getCategoryFaculty();
for(UkmLocation k : faculty) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
case '2' :
List<UkmLocation> college = db.getCategoryCollege();
for(UkmLocation k : college) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
}
i got my app working so it returns the information from a json api.
now i realize that i have to put everything in a asynch task so it doesn't crash as much
and a progress dialog is easier, only i really don't know how to do this so im wondering if somebody knows a really good tutorial or wants to edit my code a bit to get my started
package net.thinkbin;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class culture extends ListActivity {
private static final String TITLE = "Title";
private static final String AUTHOR = "Author";
private static final String VIEWS = "Views";
private static final String RATES = "Rates";
private static final String CONTENT = "Content";
final Context context = this;
JSONArray ideas = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder2);
Button view = (Button) findViewById(R.id.button1);
view.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("net.thinkbin.TUTORIAL1"));
overridePendingTransition(0, 0);
finish();
}
});
Button share = (Button) findViewById(R.id.button2);
share.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("net.thinkbin.SHARE"));
overridePendingTransition(0, 0);
finish();
}
});
Button menu = (Button) findViewById(R.id.buttonhome);
menu.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom);
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Loading...");
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.hourglass);
dialog.show();
Thread th = new Thread(new Runnable() {
public void run() {
startActivity(new Intent("net.thinkbin.MENU"));
overridePendingTransition(0, 0);
dialog.dismiss();
finish();
}
});
th.start();
}
});
ArrayAdapter<CharSequence> adapter2 = ArrayAdapter.createFromResource(
this, R.array.spinnerorder,
android.R.layout.simple_spinner_item);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner s = (Spinner) findViewById(R.id.cultureorder);
s.setAdapter(adapter2);
s.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapter2, View view,
int position, long id) {
if (position == 1) {
startActivity(new Intent("net.thinkbin.CULTURE2"));
overridePendingTransition(0, 0);
finish();
}
if (position == 2) {
startActivity(new Intent("net.thinkbin.CULTURE3"));
overridePendingTransition(0, 0);
finish();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions
.getJSONfromURL("http://www.thinkbin.net/include/api/index.php? cat=Culture&type=Newest&i=10");
try {
ideas = json.getJSONArray("Ideas");
for (int i = 0; i < ideas.length(); i++) {
JSONObject c = ideas.getJSONObject(i);
String title = c.getString(TITLE);
String author = c.getString(AUTHOR);
String views = c.getString(VIEWS);
String rates = c.getString(RATES);
String content = c.getString(CONTENT);
HashMap<String, String> map = new HashMap<String, String> ();
map.put(TITLE, "Title: " + title);
map.put(AUTHOR, "Author: " + author);
map.put(VIEWS, "Views: " + views);
map.put(RATES, "Rates: " + rates);
map.put(CONTENT, content);
mylist.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.main2,
new String[] { TITLE, AUTHOR, VIEWS, RATES, CONTENT },
new int[] { R.id.item_title, R.id.item_subtitle, R.id.item3,
R.id.item4, R.id.item5 });
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String Title2 = ((TextView) view.findViewById(R.id.item_title))
.getText().toString();
String Author2 = ((TextView) view
.findViewById(R.id.item_subtitle)).getText().toString();
String Content2 = ((TextView) view.findViewById(R.id.item5))
.getText().toString();
Intent in = new Intent(getApplicationContext(), idea.class);
overridePendingTransition(0, 0);
in.putExtra(TITLE, Title2);
in.putExtra(AUTHOR, Author2);
in.putExtra(CONTENT, Content2);
startActivity(in);
}
});
}
}
There is good class AsyncTask to do something Asyncronius in Android.
Example:
private class DownloadFilesTask extends AsyncTask
{
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
} }
http://developer.android.com/reference/android/os/AsyncTask.html