Hi all!
I've been developing an app that uses various things from my college and centralizes them in one app. I've made the app with two tabs - one for current students and one for prospective students. I would like to add the functionality of swiping between the two activities, and I saw that to do that, I want to convert my currentStudents and prospectiveStudents activities into fragments.
I have a couple of questions.
First, I don't quite understand how to accomplish converting the activities into fragments.
Second, I don't quite understand how to implement the viewPager effect.
If anyone can assist me in doing this, that'd be great. I've read through a lot of guides, but those guides are written to reflect other apps and it's pretty confusing.
Here is my MainActivity:
Code:
package com.andrew.obu;
import android.app.TabActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
public class MainActivity extends TabActivity {
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabHost tabHost = getTabHost();
TabSpec cstudents = tabHost.newTabSpec("Current Students");
cstudents.setIndicator("Students");
Intent cstudentsIntent = new Intent(this, CurrentStudents.class);
cstudents.setContent(cstudentsIntent);
TabSpec prospects = tabHost.newTabSpec("Prospectives");
prospects.setIndicator("Prospectives");
Intent prospectsIntent = new Intent(this, ProspectiveStudents.class);
prospects.setContent(prospectsIntent);
tabHost.addTab(cstudents);
tabHost.addTab(prospects);
tabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.BLACK);
tabHost.getTabWidget().getChildAt(1).setBackgroundColor(Color.BLACK);
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
@Override
public void onTabChanged(String arg0) {
TabHost tabHost = getTabHost();
setTabColor(tabHost);
}
});
setTabColor(tabHost);
}
public void setTabColor(TabHost tabhost) {
for(int i=0;i<tabhost.getTabWidget().getChildCount();i++)
tabhost.getTabWidget().getChildAt(i).setBackgroundColor(Color.BLACK); //unselected
if(tabhost.getCurrentTab()==0)
tabhost.getTabWidget().getChildAt(tabhost.getCurrentTab()).setBackgroundColor(Color.rgb(34, 34, 34)); //1st tab selected
else
tabhost.getTabWidget().getChildAt(tabhost.getCurrentTab()).setBackgroundColor(Color.rgb(34, 34, 34)); //2nd tab selected
}
}
And my code for the CurrentStudents Activity
Code:
package com.andrew.obu;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
public class CurrentStudents extends ListActivity {
private static final int MENU_ABOUT = 0;
private static final int MENU_CONTACT = 1;
int counter;
Button banner, email, moodle, jupiter, staff, calendar, athletics, news, prosp;
TextView display;
Drawable drawable;
@Override
public boolean onCreateOptionsMenu(android.view.Menu menu)
{
menu.add(0, MENU_ABOUT, 0, "About");
menu.add(0, MENU_CONTACT, 0, "Contact Me");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case MENU_ABOUT:
doSomething();
return true;
case MENU_CONTACT:
doSomethingElse();
return true;
}
return super.onOptionsItemSelected(item);
}
private void doSomethingElse() {
Intent intent = new Intent(getBaseContext(), Contact.class);
startActivity(intent);
}
private void doSomething() {
Intent intent = new Intent(getBaseContext(), About.class);
startActivity(intent);}
/*@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cstudents);*/
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] choose = getResources().getStringArray(R.array.cstudents_array);
ListView lv = getListView();
LayoutInflater lf;
View headerView;
lf = this.getLayoutInflater();
headerView = (View)lf.inflate(R.layout.cstudents, null, false);
lv.addHeaderView(headerView, null, false);
lv.setTextFilterEnabled(true);
lv.setBackgroundColor(Color.WHITE);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_content, choose));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent intent;
switch(position) {
default:
case 0 :
intent = new Intent(this, Bannerdisclaimer.class);
break;
case 2 :
intent = new Intent(this, Emailwebview.class);
break;
case 3 :
intent = new Intent(this, Moodlewebview.class);
break;
case 4 :
intent = new Intent(this, Jupiterwebview.class);
break;
case 5 :
intent = new Intent(this, Staffwebview.class);
break;
case 6 :
intent = new Intent(this, Calendar.class);
break;
case 7 :
intent = new Intent(this, Athleticswebview.class);
break;
case 8 :
intent = new Intent(this, Newswebview.class);
//intent7.putExtra("KEY_SELECTED_INDEX", position);
//startActivity(intent7);
break;
}
startActivity(intent);
};
}
//Resources res = getResources();
//drawable = res.getDrawable(R.drawable.bannera);
/*final Context context1 = this;
banner = (Button) findViewById(R.id.BannerButton);
banner.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
banner.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myWebView = new Intent(context1, Bannerwebview.class);
startActivity(myWebView);
}
});
final Context context2 = this;
email = (Button) findViewById(R.id.EmailButton);
email.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
email.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myWebView = new Intent(context2, Emailwebview.class);
startActivity(myWebView);
}
});
final Context context3 = this;
moodle = (Button) findViewById(R.id.MoodleButton);
moodle.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
moodle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myWebView = new Intent(context3, Moodlewebview.class);
startActivity(myWebView);
}
});
final Context context4 = this;
jupiter = (Button) findViewById(R.id.JupiterButton);
jupiter.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
jupiter.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myWebView = new Intent(context4, Jupiterwebview.class);
startActivity(myWebView);
}
});
final Context context5 = this;
staff = (Button) findViewById(R.id.StaffButton);
staff.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
staff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myWebView = new Intent(context5, Staffwebview.class);
startActivity(myWebView);
}
});
final Context context = this;
calendar = (Button) findViewById(R.id.CalendarButton);
calendar.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
calendar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, Calendar.class);
startActivity(intent);
}
});
final Context context6 = this;
athletics = (Button) findViewById(R.id.AthleticsButton);
athletics.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
athletics.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context6, Athleticswebview.class);
startActivity(intent);
}
});
final Context context7 = this;
news = (Button) findViewById(R.id.NewsButton);
news.getBackground().setColorFilter(Color.rgb(148, 148, 148), PorterDuff.Mode.MULTIPLY);
news.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context7, Newswebview.class);
startActivity(intent);
}
});*/
And my code for the ProspectiveStudents activity
Code:
package com.andrew.obu;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
public class ProspectiveStudents extends ListActivity
{
private static final int MENU_ABOUT = 0;
private static final int MENU_CONTACT = 1;
int counter;
Button banner, email, moodle, jupiter, staff, calendar, athletics, news, prosp;
TextView display;
Drawable drawable;
@Override
public boolean onCreateOptionsMenu(android.view.Menu menu)
{
menu.add(0, MENU_ABOUT, 0, "About");
menu.add(0, MENU_CONTACT, 0, "Contact Me");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case MENU_ABOUT:
doSomething();
return true;
case MENU_CONTACT:
doSomethingElse();
return true;
}
return super.onOptionsItemSelected(item);
}
private void doSomethingElse() {
Intent intent = new Intent(getBaseContext(), Contact.class);
startActivity(intent);
}
private void doSomething() {
Intent intent = new Intent(getBaseContext(), About.class);
startActivity(intent);}
/*@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cstudents);*/
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] choose = getResources().getStringArray(R.array.pstudents_array);
ListView lv = getListView();
LayoutInflater lf;
View headerView;
lf = this.getLayoutInflater();
headerView = (View)lf.inflate(R.layout.cstudents, null, false);
lv.addHeaderView(headerView, null, false);
lv.setTextFilterEnabled(true);
lv.setBackgroundColor(Color.WHITE);
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_content, choose));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent intent;
switch(position) {
default:
case 0 :
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.okbu.edu/admissions/onlineapp.html"));
break;
case 2 :
intent = new Intent(this, Majors.class);
break;
case 3 :
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.okbu.edu/admissions/moreinfo.html"));
break;
case 4 :
intent = new Intent(this, Visitwebview.class);
break;
/*case 5 :
intent = new Intent(this, Getinvolved.class);
break;*/
}
startActivity(intent);
};
}
I recommend you to use ActionBarSherlock library: http://actionbarsherlock.com
Take a look at the samples and it will be easy to do what you ask for. At first, it may take a while to learn how to use this library, but you will not regret it since you will use it several times in the future for sure.
The coolest thing about this library is that it is compatible with older Android versions. I.e. The swipe effect will be available for Ice Cream users while for Froyo users will see two clickable tabs :good:
First of all, you can't swipe between activities. You can only swipe between fragments. Think of the activity as a container which holds your two fragments.
This is an example of a ListFragment:
Code:
public static class TitlesFragment extends ListFragment {
boolean mDualPane;
int mCurCheckPosition = 0;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Populate list with our static array of titles.
setListAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_activated_1, Shakespeare.TITLES));
// Check to see if we have a frame in which to embed the details
// fragment directly in the containing UI.
View detailsFrame = getActivity().findViewById(R.id.details);
mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;
if (savedInstanceState != null) {
// Restore last state for checked position.
mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
}
if (mDualPane) {
// In dual-pane mode, the list view highlights the selected item.
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
// Make sure our UI is in the correct state.
showDetails(mCurCheckPosition);
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
showDetails(position);
}
/**
* Helper function to show the details of a selected item, either by
* displaying a fragment in-place in the current UI, or starting a
* whole new activity in which it is displayed.
*/
void showDetails(int index) {
mCurCheckPosition = index;
if (mDualPane) {
// We can display everything in-place with fragments, so update
// the list to highlight the selected item and show the data.
getListView().setItemChecked(index, true);
// Check what fragment is currently shown, replace if needed.
DetailsFragment details = (DetailsFragment)
getFragmentManager().findFragmentById(R.id.details);
if (details == null || details.getShownIndex() != index) {
// Make new fragment to show this selection.
details = DetailsFragment.newInstance(index);
// Execute a transaction, replacing any existing fragment
// with this one inside the frame.
FragmentTransaction ft = getFragmentManager().beginTransaction();
if (index == 0) {
ft.replace(R.id.details, details);
} else {
ft.replace(R.id.a_item, details);
}
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
} else {
// Otherwise we need to launch a new activity to display
// the dialog fragment with selected text.
Intent intent = new Intent();
intent.setClass(getActivity(), DetailsActivity.class);
intent.putExtra("index", index);
startActivity(intent);
}
}
}
I can't help you there because I've never worked with lists.
As for the swiping effect, build your project with a minimum SDK of 14 (ICS) and choose swipe-able tabs navigation. The ADT will do the job for you. Later, in order to maintain compatibility, use ABS library as patedit suggested.
Good luck
To implement a ViewPager, just add ViewPager to XML layout, and set a FragmentPageAdapter to it.
You must use support package from Android SDK and FragmentActivity instead of Activitiy.
You can examine source code of API Demos package to know more.
package com.example.project10;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final String SOAP_ACTION = "http://Sample/customerData/";
private static final String METHOD_NAME = "customerData";
private static final String NAMESPACE = "http://Sample";
private static final String URL = "http://192.168.1.16:8080/Project10/services/SampleMain?wsdl";
/** Called when the activity is first created. */
private Thread thread;
public TextView tv;
public String resultArr[];
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv =(TextView)findViewById(R.id.textView1);
startWebAccess();
//for(int i = 0; i<resultArr.length;i++){
// tv.append(resultArr+"\n\n");
// }
// setContentView(tv);
}
public void startWebAccess(){
thread = new Thread(){
public void run(){
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE ht = new HttpTransportSE(URL);
try {
ht.call(SOAP_ACTION, envelope);
Object response= envelope.getResponse();
//SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
//SoapPrimitive s = response;
String str = response.toString();
System.out.println(str);
if(str!=null){
System.out.println(".....");
}
String resultArr[] = str.split("&");//Result string will split & store in an array
for(int i = 0; i<resultArr.length;i++){
tv.append(resultArr+"\n\n");
// tv.append(str);
}
setContentView(tv);
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
}
@override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
This is my source code ,i am getting error so help me..
Magesh.K said:
package com.example.project10;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final String SOAP_ACTION = "http://Sample/customerData/";
private static final String METHOD_NAME = "customerData";
private static final String NAMESPACE = "http://Sample";
private static final String URL = "http://192.168.1.16:8080/Project10/services/SampleMain?wsdl";
/** Called when the activity is first created. */
private Thread thread;
public TextView tv;
public String resultArr[];
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv =(TextView)findViewById(R.id.textView1);
startWebAccess();
//for(int i = 0; i<resultArr.length;i++){
// tv.append(resultArr+"\n\n");
// }
// setContentView(tv);
}
public void startWebAccess(){
thread = new Thread(){
public void run(){
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE ht = new HttpTransportSE(URL);
try {
ht.call(SOAP_ACTION, envelope);
Object response= envelope.getResponse();
//SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
//SoapPrimitive s = response;
String str = response.toString();
System.out.println(str);
if(str!=null){
System.out.println(".....");
}
String resultArr[] = str.split("&");//Result string will split & store in an array
for(int i = 0; i<resultArr.length;i++){
tv.append(resultArr+"\n\n");
// tv.append(str);
}
setContentView(tv);
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
}
@override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
This is my source code ,i am getting error so help me..
Click to expand...
Click to collapse
What is the error that you're getting ? .. A logcat would be appreciated !
This is a rudimentary android application that serves as an umpires strike/ball/out counter. There is a settings icon in the action bar of the MainActivity. When this icon is 'clicked on', a new Activity is started consisting of a PreferenceFragment, which consists of a checkboxpreference, and a Fragment that consists of 3 buttons. These buttons reset the stike_count, ball_count and total_outs_count to zero. I have spent a day on this and am having trouble figuring out how to manipulate integer variables in my MainActivity from button clicks in a seperate Activity's Fragment. Please point me in the right direction.
package edu.umkc.baldwin;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final String TAG = "UmpireActivity";
// Constant variables declared/initialized to keep track of values
// across lifecycle states
@SuppressWarnings("unused")
private static final String STRIKES = "0";
@SuppressWarnings("unused")
private static final String BALLS = "0";
@SuppressWarnings("unused")
private static final String OUTS = "0";
TextView strikeCounterTV;
TextView ballCounterTV;
TextView totalOutCounterTV;
private Button strikeCounterButton;
private Button ballCounterButton;
private int strike_count;
private int ball_count;
private int out_count;
private void updateViews(){
strikeCounterTV.setText(String.valueOf(strike_count));
ballCounterTV.setText(String.valueOf(ball_count));
totalOutCounterTV.setText(String.valueOf(out_count));
}
private void displayToast(boolean x){
int messageId = 0;
if (x == true){
messageId = R.string.strike_toast_view;
} else {
messageId = R.string.ball_toast_view;
}
Toast toast = Toast.makeText(MainActivity.this, messageId,
Toast.LENGTH_SHORT);
LinearLayout toastLayout = (LinearLayout) toast.getView();
TextView toastTV = (TextView) toastLayout.getChildAt(0);
toast.setGravity(Gravity.CENTER|Gravity.CENTER, 0, -150);
toastTV.setTextSize(42);
toast.show();
}
/*
* (non-Javadoc)
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "OnCreate(Bundle) called");
setContentView(R.layout.main_page_layout);
//Declare TextView objects and Button objects
strikeCounterTV = (TextView) findViewById(R.id.strikeCountTextView);
ballCounterTV = (TextView) findViewById(R.id.ballCountTextView);
totalOutCounterTV = (TextView) findViewById(R.id.totalOutsTextViewCounter);
strikeCounterButton = (Button) findViewById(R.id.strikeCountButton);
ballCounterButton = (Button) findViewById(R.id.ballCountButton);
strikeCounterButton.setOnClickListener(new OnClickListener(){
@override
public void onClick(View v) {
if (strike_count < 2){
strike_count++;
updateViews();
} else {
// batter has reached strike limit
displayToast(true);
out_count++;
strike_count = 0;
ball_count = 0;
updateViews();
}
}
});
ballCounterButton.setOnClickListener(new OnClickListener(){
@override
public void onClick(View v) {
if (ball_count < 3){
ball_count++;
updateViews();
} else {
// batter has reached ball limit
displayToast(false);
strike_count = 0;
ball_count = 0;
updateViews();
}
}
});
// Check for screen rotation
if (savedInstanceState == null){
strike_count = 0;
ball_count = 0;
} else {
strike_count = savedInstanceState.getInt("STRIKES");
ball_count = savedInstanceState.getInt("BALLS");
}
// Save 'totalOuts' variable through application exit
SharedPreferences savedObject = getPreferences(Context.MODE_PRIVATE);
out_count = savedObject.getInt(getString(R.string.total_outs_key), 0);
updateViews();
}
@override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
Log.d(TAG, "onSaveInstanceState() called");
savedInstanceState.putInt("STRIKES", strike_count);
savedInstanceState.putInt("BALLS", ball_count);
savedInstanceState.putInt("OUTS", out_count);
}
@override
public boolean onCreateOptionsMenu(Menu menu) {
//Displays actionbar items in app actionbar
getMenuInflater().inflate(R.menu.actionbar_layout, menu);
return super.onCreateOptionsMenu(menu);
}
@override
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
switch (item.getItemId()){
case (R.id.reset_option):
strike_count = 0;
ball_count = 0;
updateViews();
return true;
case (R.id.about_menu_option):
Intent i = new Intent(this, About.class);
startActivity(i);
return true;
case (R.id.settings_menu_option):
Intent j = new Intent(this, SettingsActivity.class);
startActivity(j);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@override
public void onStart() {
super.onStart();
Log.d(TAG, "onStart() called");
}
@override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause() called");
}
@override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume() called");
}
@override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop() called");
SharedPreferences out_file = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = out_file.edit();
editor.putInt(getString(R.string.total_outs_key), out_count);
editor.commit();
}
@override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() called");
}
}
package edu.umkc.baldwin;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
public class SettingsActivity extends Activity {
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_layout);
FragmentManager ttsFragmentManager = getFragmentManager();
FragmentTransaction ttsFragmentTransaction = ttsFragmentManager.beginTransaction();
EnableTTSPreferenceFragment ttsFragment = new EnableTTSPreferenceFragment();
ttsFragmentTransaction.add(R.id.tts_fragment, ttsFragment);
ttsFragmentTransaction.commit();
FragmentManager resetFragmentManager = getFragmentManager();
FragmentTransaction resetFragmentTransaction = resetFragmentManager.beginTransaction();
ResetFragment resetFragment = new ResetFragment();
resetFragmentTransaction.add(R.id.reset_fragment, resetFragment);
resetFragmentTransaction.commit();
}
}
package edu.umkc.baldwin;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ResetFragment extends Fragment {
@override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View resetFragment = inflater.inflate(R.layout.reset_layout, container, false);
return resetFragment;
}
}
package edu.umkc.baldwin;
import android.os.Bundle;
import android.preference.PreferenceFragment;
public class EnableTTSPreferenceFragment extends PreferenceFragment {
@override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.tts_preference_fragment);
}
@override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
}
To modify anything in your activity from one of its child Fragments you would typically create an interface in the Fragment and have the activity implement that. That interface would either contain one method setting all three vars or multiple ones, one for each variable. To call the methods in the interface call getActivity() and typecast it to the interface.
In my app i just have a splash screen and a main activity. In the main thread i have three EditText boxes and a spinner with a string array. On clicking the Button, input from three EditText and spinner selection is posted to my mysql database. For the button click network operation, i used Volley since its east and i dont have to use AsyncTask which am not familiar with.
Apart from this, on entering the main UI .. app first check for network connectivity using ConnectivityManager class. After onClick app checks for empty/invalid imputs using TextUtils.
Now the problem is that when i run my app, its very slow and taking upto 65mb of RAM. IS something wrong with my code. Should i run something else as AsynTask ? Can someone check my code and refine it .. thank you
SplashActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class SplashActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
int SPLASH_TIME_OUT = 5000;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent i = new Intent(SplashActivity.this, MainActivity.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
}
Click to expand...
Click to collapse
MainActivity.java
Code:
public class MainActivity extends Activity {
EditText name, phonenumber, address;
Button insert;
RequestQueue requestQueue;
Spinner spinner;
String insertUrl = "localhost";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner s = (Spinner) findViewById(R.id.spinner);
s.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
/* CHECK INTERNET CONNECTION */
boolean mobileNwInfo;
ConnectivityManager conxMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
try { mobileNwInfo = conxMgr.getActiveNetworkInfo().isConnected(); }
catch (NullPointerException e) { mobileNwInfo = false; }
if (!mobileNwInfo) {
Toast.makeText(this, "No Network, please check your connection. ", Toast.LENGTH_LONG).show();
}
/* CHECK INTERNET CONNECTION PROCEDURE DONE */
name = (EditText) findViewById(R.id.editText);
phonenumber= (EditText) findViewById(R.id.editText2);
address = (EditText) findViewById(R.id.editText3);
insert = (Button) findViewById(R.id.insert);
requestQueue = Volley.newRequestQueue(getApplicationContext());
spinner = (Spinner) findViewById(R.id.spinner);
insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/* CHECK EMPTY STRING */
EditText txtUserName = (EditText) findViewById(R.id.editText);
EditText txtUserAddress = (EditText) findViewById(R.id.editText3);
EditText txtUserPhone = (EditText) findViewById(R.id.editText2);
String strUserName = name.getText().toString();
String strUserAddress = address.getText().toString();
String strUserPhone = phonenumber.getText().toString();
if(TextUtils.isEmpty(strUserName)) {
txtUserName.setError("You can't leave this empty.");
return;
}
if(TextUtils.isEmpty(strUserPhone)) {
txtUserPhone.setError("You can't leave this empty.");
return;
}
if(TextUtils.isEmpty(strUserPhone) || strUserPhone.length() < 10) {
txtUserPhone.setError("Enter a valid phone number.");
return;
}
if(TextUtils.isEmpty(strUserAddress)) {
txtUserAddress.setError("You can't leave this empty.");
return;
}
/* LOADING PROCESS DIALOG */
final ProgressDialog pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Booking Service ....");
pd.show();
/* REQUEST RESPONSE/ERROR */
StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
pd.hide();
System.out.println(response);
name.setText("");
phonenumber.setText("");
address.setText("");
Toast.makeText(getApplicationContext(), "Service successfully booked !!", Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
pd.hide();
Toast.makeText(getApplicationContext(), "Error: Please try again later.", Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<>();
parameters.put("name", name.getText().toString());
parameters.put("phonenumber", phonenumber.getText().toString());
parameters.put("address", address.getText().toString());
parameters.put("service", spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString());
return parameters;
}
};
requestQueue.add(request);
}
});
}
}
Well it's hard to say what exactly is wrong with it. Maybe text is to long. You can try to measure each operation performance with System.nanoseconds(easiest) and localize the problem first. It would be easier to say what to do with it.
Yes you should try to figure out what part is causing the problem. Try to cut the code down to essentials and measure the execution time. Maybe you will be able to tell what part exactly is not working as wanted.
I have a problem with the pictures when I use the search then the app always takes the first picture instead of the picture that belongs.
I added two pictures where you can see what I mean by "Adrenaline".
Can someone help me by chance?
I would be very happy.
Sorry for my bad English.
Code:
package com.0000.00000;
import androidx.appcompat.app.AppCompatActivity;
import android.app.*;
import android.os.*;
import android.view.*;
import android.view.View.*;
import android.widget.*;
import android.content.*;
import android.graphics.*;
import android.media.*;
import android.net.*;
import android.text.*;
import android.util.*;
import android.webkit.*;
import android.animation.*;
import android.view.animation.*;
import java.util.*;
import java.text.*;
import java.util.HashMap;
import java.util.ArrayList;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.AdRequest;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.AdListener;
import android.content.Intent;
import android.net.Uri;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.AdapterView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class PerksActivity extends Activity {
private ArrayList<Integer> image_list = new ArrayList<>();
private HashMap<String, Object> map_var = new HashMap<>();
private String saved = "";
private double length = 0;
private double r = 0;
private String value1 = "";
private String value2 = "";
private String value3 = "";
private String value4 = "";
private ArrayList<HashMap<String, Object>> map_list = new ArrayList<>();
private LinearLayout linear1;
private LinearLayout linear2;
private LinearLayout linear3;
private LinearLayout linear10;
private LinearLayout linear11;
private LinearLayout linear12;
private TextView textview4;
private AdView adview1;
private LinearLayout linear15;
private LinearLayout linear16;
private LinearLayout linear44;
private ListView listview1;
private EditText edittext1;
private LinearLayout linear929;
private TextView textview8;
private InterstitialAd admob;
private AdListener _admob_ad_listener;
private Intent page_intent = new Intent();
private AlertDialog.Builder popup;
@Override
protected void onCreate(Bundle _savedInstanceState) {
super.onCreate(_savedInstanceState);
setContentView(R.layout.perks);
initialize(_savedInstanceState);
initializeLogic();
}
private void initialize(Bundle _savedInstanceState) {
linear1 = (LinearLayout) findViewById(R.id.linear1);
linear2 = (LinearLayout) findViewById(R.id.linear2);
linear3 = (LinearLayout) findViewById(R.id.linear3);
linear10 = (LinearLayout) findViewById(R.id.linear10);
linear11 = (LinearLayout) findViewById(R.id.linear11);
linear12 = (LinearLayout) findViewById(R.id.linear12);
textview4 = (TextView) findViewById(R.id.textview4);
adview1 = (AdView) findViewById(R.id.adview1);
linear15 = (LinearLayout) findViewById(R.id.linear15);
linear16 = (LinearLayout) findViewById(R.id.linear16);
linear44 = (LinearLayout) findViewById(R.id.linear44);
listview1 = (ListView) findViewById(R.id.listview1);
edittext1 = (EditText) findViewById(R.id.edittext1);
linear929 = (LinearLayout) findViewById(R.id.linear929);
textview8 = (TextView) findViewById(R.id.textview8);
popup = new AlertDialog.Builder(this);
listview1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> _param1, View _param2, int _param3, long _param4) {
final int _position = _param3;
if (_position == 0) {
popup.setTitle(map_list.get((int)_position).get("d").toString());
popup.setMessage(map_list.get((int)_position).get("e").toString());
popup.setPositiveButton("Schliessen", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface _dialog, int _which) {
}
});
popup.create().show();
}
if (_position == 1) {
popup.setTitle(map_list.get((int)_position).get("d").toString());
popup.setMessage(map_list.get((int)_position).get("e").toString());
popup.setPositiveButton("Schliessen", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface _dialog, int _which) {
}
});
popup.create().show();
}
if (_position == 2) {
popup.setTitle(map_list.get((int)_position).get("d").toString());
popup.setMessage(map_list.get((int)_position).get("e").toString());
popup.setPositiveButton("Schliessen", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface _dialog, int _which) {
}
});
popup.create().show();
}
}
});
edittext1.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence _param1, int _param2, int _param3, int _param4) {
final String _charSeq = _param1.toString();
map_list = new Gson().fromJson(saved, new TypeToken<ArrayList<HashMap<String, Object>>>(){}.getType());
length = map_list.size();
r = length - 1;
for(int _repeat17 = 0; _repeat17 < (int)(length); _repeat17++) {
value1 = map_list.get((int)r).get("a").toString();
value2 = map_list.get((int)r).get("b").toString();
value3 = map_list.get((int)r).get("c").toString();
if (!(_charSeq.length() > value1.length()) && value1.toLowerCase().contains(_charSeq.toLowerCase())) {
}
else {
if (!(_charSeq.length() > value2.length()) && value2.toLowerCase().contains(_charSeq.toLowerCase())) {
}
else {
if (!(_charSeq.length() > value3.length()) && value3.toLowerCase().contains(_charSeq.toLowerCase())) {
}
else {
map_list.remove((int)(r));
}
}
}
r--;
}
listview1.setAdapter(new Listview1Adapter(map_list));
((BaseAdapter)listview1.getAdapter()).notifyDataSetChanged();
}
@Override
public void beforeTextChanged(CharSequence _param1, int _param2, int _param3, int _param4) {
}
@Override
public void afterTextChanged(Editable _param1) {
}
});
_admob_ad_listener = new AdListener() {
@Override
public void onAdLoaded() {
admob.show();
}
@Override
public void onAdFailedToLoad(int _param1) {
final int _errorCode = _param1;
SketchwareUtil.showMessage(getApplicationContext(), "Werbung konnte nicht Geladen werden!!!".concat(String.valueOf((long)(_errorCode))));
}
@Override
public void onAdOpened() {
}
@Override
public void onAdClosed() {
}
};
}
private void initializeLogic() {
adview1.loadAd(new AdRequest.Builder().addTestDevice("0815")
.build());
map_var = new HashMap<>();
map_var.put("a", getResources().getString(R.string.perksstriche));
map_var.put("b", getResources().getString(R.string.perksueberlebende));
map_var.put("c", getResources().getString(R.string.perksstriche02));
map_var.put("d", getResources().getString(R.string.perksinfopopupheadername));
map_var.put("e", getResources().getString(R.string.perksinfopopuptxtname));
map_list.add(map_var);
map_var = new HashMap<>();
map_var.put("a", getResources().getString(R.string.perkablenkungname));
map_var.put("b", getResources().getString(R.string.perksueberlebendenadamfrancisname));
map_var.put("c", getResources().getString(R.string.perkslehrbarimblutnetzlevel30name));
map_var.put("d", getResources().getString(R.string.perkablenkungpopupheadername));
map_var.put("e", getResources().getString(R.string.perkablenkungpopuptxt));
map_list.add(map_var);
map_var = new HashMap<>();
map_var.put("a", getResources().getString(R.string.perkadrenalinname));
map_var.put("b", getResources().getString(R.string.perksueberlebendenmegthomasname));
map_var.put("c", getResources().getString(R.string.perkslehrbarimblutnetzlevel40name));
map_var.put("d", getResources().getString(R.string.perkadrenalinpopupheadername));
map_var.put("e", getResources().getString(R.string.perkadrenalinpopuptxt));
map_list.add(map_var);
listview1.setAdapter(new Listview1Adapter(map_list));
((BaseAdapter)listview1.getAdapter()).notifyDataSetChanged();
saved = new Gson().toJson(map_list);
image_list.add(R.drawable.perk_ueberlebende);
image_list.add(R.drawable.adam_francis_perk_ablenkung);
image_list.add(R.drawable.meg_thomas_perk_adrenalin);
}
@Override
protected void onActivityResult(int _requestCode, int _resultCode, Intent _data) {
super.onActivityResult(_requestCode, _resultCode, _data);
switch (_requestCode) {
default:
break;
}
}
public class Listview1Adapter extends BaseAdapter {
ArrayList<HashMap<String, Object>> _data;
public Listview1Adapter(ArrayList<HashMap<String, Object>> _arr) {
_data = _arr;
}
@Override
public int getCount() {
return _data.size();
}
@Override
public HashMap<String, Object> getItem(int _index) {
return _data.get(_index);
}
@Override
public long getItemId(int _index) {
return _index;
}
@Override
public View getView(final int _position, View _view, ViewGroup _viewGroup) {
LayoutInflater _inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View _v = _view;
if (_v == null) {
_v = _inflater.inflate(R.layout.perkssearch, null);
}
final LinearLayout linear1 = (LinearLayout) _v.findViewById(R.id.linear1);
final ImageView imageview1 = (ImageView) _v.findViewById(R.id.imageview1);
final LinearLayout linear2 = (LinearLayout) _v.findViewById(R.id.linear2);
final LinearLayout linear3 = (LinearLayout) _v.findViewById(R.id.linear3);
final TextView textview1 = (TextView) _v.findViewById(R.id.textview1);
final TextView textview2 = (TextView) _v.findViewById(R.id.textview2);
final TextView textview3 = (TextView) _v.findViewById(R.id.textview3);
textview1.setText(map_list.get((int)_position).get("a").toString());
textview2.setText(map_list.get((int)_position).get("b").toString());
textview3.setText(map_list.get((int)_position).get("c").toString());
imageview1.setImageResource(image_list.get((int)_position));
if (textview2.getText().equals(getResources().getString(R.string.perksueberlebende)) ) {
textview2.setTextColor(0xFFFFFFFF);
}
if (textview2.getText().equals(getResources().getString(R.string.perksvonkeinezuordnungname)) ) {
textview2.setTextColor(0xFFFFFFFF);
}
if (textview2.getText().equals(getResources().getString(R.string.perksueberlebendendwightfairfieldname)) ) {
textview2.setTextColor(0xFF8BC34A);
}
return _v;
}
}
@Deprecated
public void showMessage(String _s) {
Toast.makeText(getApplicationContext(), _s, Toast.LENGTH_SHORT).show();
}
@Deprecated
public int getLocationX(View _v) {
int _location[] = new int[2];
_v.getLocationInWindow(_location);
return _location[0];
}
@Deprecated
public int getLocationY(View _v) {
int _location[] = new int[2];
_v.getLocationInWindow(_location);
return _location[1];
}
@Deprecated
public int getRandom(int _min, int _max) {
Random random = new Random();
return random.nextInt(_max - _min + 1) + _min;
}
@Deprecated
public ArrayList<Double> getCheckedItemPositionsToArray(ListView _list) {
ArrayList<Double> _result = new ArrayList<Double>();
SparseBooleanArray _arr = _list.getCheckedItemPositions();
for (int _iIdx = 0; _iIdx < _arr.size(); _iIdx++) {
if (_arr.valueAt(_iIdx))
_result.add((double)_arr.keyAt(_iIdx));
}
return _result;
}
@Deprecated
public float getDip(int _input){
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, _input, getResources().getDisplayMetrics());
}
@Deprecated
public int getDisplayWidthPixels(){
return getResources().getDisplayMetrics().widthPixels;
}
@Deprecated
public int getDisplayHeightPixels(){
return getResources().getDisplayMetrics().heightPixels;
}
}