i am trying to bind data on a expandable listview. A new thread has been called because of too much load on the main thread during populate a map from database.
MY problem is, expandable list view is not showing after new thread
execution but if i set a break point on the adapter initialization ,
it working fine..i tried notifyDataSetChanged() but no luck
Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
selectedvalue = extras.getString("selected_data");
if (selectedvalue != null) {
TextView textView=(TextView)findViewById(R.id.textView2SelectedData);
textView.setText(selectedvalue);
textView.setBackgroundResource(R.color.colorAccent);
}
fillData();
ExpandableListView expandableListview =(ExpandableListView)findViewById(R.id.ExpandablelistSelectedData);
ExpandableListAdapter expandableListAdapter=new CustomAdapterExpandableList(this,manufacturerUnique,relatedMedicine);
expandableListview.setAdapter(expandableListAdapter);
}
public void fillData(){
manufacturerUnique=new ArrayList<>();
relatedMedList=new ArrayList<>();
relatedMedicine=new HashMap<>();
dbHelper=new DBHelper(this);
mProgressDialog = ProgressDialog.show(this, "Please wait","Loading...", false);
new Thread() {
#Override
public void run() {
try {
manufacturerUnique=dbHelper.getManfacturerNameListusingBrandOrGenericName(selectedvalue);
System.out.println("manufacturerUnique size"+manufacturerUnique.size());
for(int i=0;i<manufacturerUnique.size();i++){
relatedMedicine.put(manufacturerUnique.get(i),dbHelper.getBrandNameUsingSelectedItemAndmanfacturerName(selectedvalue,manufacturerUnique.get(i)));
System.out.println("manufacturerUnique added:"+manufacturerUnique.get(i));
}
System.out.println("related:"+relatedMedicine.size());
runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressDialog.dismiss();
}
});
} catch (final Exception ex) {
Log.i("---","Exception in thread");
}
}
}.start();
}
}
What am i doing wrong here? I would greatly appreciate any feedback or pointing to a similar problem like this,thanks.
edit:
public class ResultActivity extends AppCompatActivity {
private DBHelper dbHelper=null;
ExpandableListView expandableListview;
String selectedvalue="";
List<String> manufacturerUnique;
List<String>relatedMedList;
Map<String,ArrayList<String>>relatedMedicine;
//ExpandableListAdapter expandableListAdapter;
BaseExpandableListAdapter expandableListAdapter;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
selectedvalue = extras.getString("selected_data");
if (selectedvalue != null) {
TextView textView=(TextView)findViewById(R.id.textView2SelectedData);
textView.setText(selectedvalue);
textView.setBackgroundResource(R.color.colorAccent);
}
fillData();
ExpandableListView expandableListview =(ExpandableListView)findViewById(R.id.ExpandablelistSelectedData);
expandableListAdapter=new CustomAdapterExpandableList(this,manufacturerUnique,relatedMedicine);
// expandableListAdapter.notifyDataSetChanged();
expandableListview.setAdapter(expandableListAdapter);
}
public void fillData(){
manufacturerUnique=new ArrayList<>();
relatedMedList=new ArrayList<>();
relatedMedicine=new HashMap<>();
dbHelper=new DBHelper(this);
mProgressDialog = ProgressDialog.show(this, "Please wait","Loading...", false);
new Thread() {
#Override
public void run() {
try {
manufacturerUnique=dbHelper.getManfacturerNameListusingBrandOrGenericName(selectedvalue);
System.out.println("manufacturerUnique size"+manufacturerUnique.size());
for(int i=0;i<manufacturerUnique.size();i++){
relatedMedicine.put(manufacturerUnique.get(i),dbHelper.getBrandNameUsingSelectedItemAndmanfacturerName(selectedvalue,manufacturerUnique.get(i)));
System.out.println("manufacturerUnique added:"+manufacturerUnique.get(i));
}
System.out.println("related:"+relatedMedicine.size());
// expandableListAdapter.notifyDataSetChanged();// exception
runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressDialog.dismiss();
expandableListAdapter.notifyDataSetChanged();
}
});
} catch (final Exception ex) {
Log.i("---",ex.toString());
}
}
}.start();
}
}
Related
I am trying to get the data to next activity using Bundle and putString. But the data fail to carry to the next page. Below is part of my coding:
public class assessment_table_edit extends AppCompatActivity {
Toolbar toolbar;
String data = "";
TableLayout tlAssessment;
TableRow tr;
TextView stuID,totalmarks,marks,edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_assessment_table_edit);
toolbar=(Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Percentage of the Marks");
tlAssessment=(TableLayout)findViewById(R.id.tlAssessment_Edit);
final Assessment_Information_GetData getdb=new Assessment_Information_GetData();
new Thread(new Runnable() {
#Override
public void run() {
data =getdb.getDataFromDB();
System.out.println(data);
runOnUiThread(new Runnable() {
#Override
public void run() {
ArrayList<Assessment_Information> users=parseJSON(data);
addData(users);
}
});
}
}).start();
if(getSupportActionBar()!=null){
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
View.OnClickListener onClickListener=new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.assessment_id:
Assessment_Information user=new Assessment_Information();
Intent iChange=new Intent(assessment_table_edit.this,assessment_edit_data.class);
Bundle b=new Bundle();
b.putString("stuID",user.getStuID());
iChange.putExtras(b);
// iChange.putExtra("stuID",user.getStuID());
startActivity(iChange);
break;
}
}
};
public ArrayList<Assessment_Information>parseJSON(String result){
ArrayList<Assessment_Information> users=new ArrayList<Assessment_Information>();
try {
JSONObject jsonObject=new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("posts");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json_data = jsonArray.getJSONObject(i);
Assessment_Information user=new Assessment_Information();
user.setStuID(json_data.getString("stuID"));
user.setTotalmarks(json_data.getString("totalmarks"));
user.setMarks(json_data.getString("marks"));
users.add(user);
}
}catch (JSONException e){
Log.e("log_tag", "Error parsing data " + e.toString());
}
return users;
}
When I replace user.getString() to "check" for testing, it managed to show in the next activity(assessment_edit_data).
This is assessment_edit_data.java:
public class assessment_edit_data extends AppCompatActivity {
TextView tvMatrix;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_assessment_edit_data);
tvMatrix=(TextView)findViewById(R.id.edit_data_assessment);
Bundle bundle=getIntent().getExtras();
String stuID=bundle.getString("stuID");
tvMatrix.setText(stuID);
}
My Assessment_Information.java:
public class Assessment_Information {
String stuID;
String totalmarks;
String marks;
public String getStuID() {
return stuID;
}
public void setStuID(String stuID) {
this.stuID = stuID;
}
public String getTotalmarks() {
return totalmarks;
}
public void setTotalmarks(String totalmarks) {
this.totalmarks = totalmarks;
}
public String getMarks() {
return marks;
}
public void setMarks(String marks) {
this.marks = marks;
}
}
Use this code to send data to another activity:
Intent intent = new Intent(context, YourActivity.class);
intent.putExtra("key", "value");
intent.putExtra("key2", "value2");
startActivity(intent);
And use this code to get the data in the other Activity:
Bundle bundle = getIntent().getExtras();
if(bundle!=null){
String value1 = bundle.getString("key");
String value2 = bundle.getString("key2");
}
You can check if your bundle contains the key:
if(bundle.containsKey("key")){
//...
}
UPDATE
You're creating a new user without any data (it seems)
Assessment_Information user=new Assessment_Information(); //This user has data?
Intent iChange=new Intent(assessment_table_edit.this,assessment_edit_data.class);
Bundle b=new Bundle();
b.putString("stuID",user.getStuID()); // user.getStuID() probably is null
I don't see in your class Assessment_Information a constructor where you insert data to the stuID variable.
UPDATE
Try this part of code:
public class assessment_table_edit extends AppCompatActivity {
Toolbar toolbar;
String data = "";
TableLayout tlAssessment;
TableRow tr;
TextView stuID,totalmarks,marks,edit;
ArrayList<Assessment_Information> users;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_assessment_table_edit);
toolbar=(Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Percentage of the Marks");
tlAssessment=(TableLayout)findViewById(R.id.tlAssessment_Edit);
final Assessment_Information_GetData getdb=new Assessment_Information_GetData();
new Thread(new Runnable() {
#Override
public void run() {
data =getdb.getDataFromDB();
System.out.println(data);
runOnUiThread(new Runnable() {
#Override
public void run() {
users=parseJSON(data);
addData(users);
}
});
}
}).start();
if(getSupportActionBar()!=null){
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
View.OnClickListener onClickListener=new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.assessment_id:
Intent iChange=new Intent(assessment_table_edit.this,assessment_edit_data.class);
Bundle b=new Bundle();
b.putString("stuID", users.get(0).getStuID());
// If you want to send more than the first user
//for(int i=0; users.size() < i ; i++) {
// b.putString("stuID"+i, users.get(i).getStuID());
//}
//b.putInt("numberOfUsers", users.size());
iChange.putExtras(b);
// iChange.putExtra("stuID",user.getStuID());
startActivity(iChange);
break;
}
}
};
The problem it is you instantiate the user object but never retrieve the data. The user is as you declared it in the class.
At least you should read the data from you db and set it to the new object.
This is right way to putExtra and getExtra some data in Android.
Use this to "put" the file...
Intent i = new Intent(FirstScreen.this, SecondScreen.class);
String strName = null;
i.putExtra("STRING_I_NEED", strName);
Then, to retrieve the value try something like:
String newString;
Bundle extras = getIntent().getExtras();
if(extras == null) {
newString= null;
} else {
newString= extras.getString("STRING_I_NEED");
}
Bonus Suggestion :
I can see your class name is assessment_edit_data.
Make it like AssessmentEditData as Java suggest naming convention.
Kleorence,
I was shocked to see your huge code for adding a new row. I am giving you my code to add a new row with your desired styles and themes.
Pros:
Just code in .xml as you always do.
No need to code in java for styling rows.
in onCreate
TableLayout tableLayout = (TableLayout) findViewById(R.id.tlpromote);
private void addNewRow() {
// instantiate a tableRow
TableRow row = new TableRow(context);
// inflate your custom view on it.
View v = LayoutInflater.from(context).inflate(R.layout.table_row, row, false);
// put your values in its views
TextView tvTable_sr = (TextView) v.findViewById(R.id.tvTable_sr);
TextView tvTable_title = (TextView) v.findViewById(R.id.tvTable_title);
//add your custom view to row
tableLayout.addView(v);
}
Here table_row is your row with custom view.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<!--make any view you want-->
</LinearLayout>
I hope you find this very helpful.
The problem is that you are populating the data in an array but when passing the object to another activity, you are creating a brand-new object in which every field is null.
public class assessment_table_edit extends AppCompatActivity {
Toolbar toolbar;
String data = "";
TableLayout tlAssessment;
TableRow tr;
TextView stuID,totalmarks,marks,edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_assessment_table_edit);
toolbar=(Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Percentage of the Marks");
tlAssessment=(TableLayout)findViewById(R.id.tlAssessment_Edit);
//You are populating data here.
final Assessment_Information_GetData getdb=new Assessment_Information_GetData();
new Thread(new Runnable() {
#Override
public void run() {
data =getdb.getDataFromDB();
System.out.println(data);
runOnUiThread(new Runnable() {
#Override
public void run() {
ArrayList<Assessment_Information> users=parseJSON(data);
addData(users);
}
});
}
}).start();
if(getSupportActionBar()!=null){
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
View.OnClickListener onClickListener=new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.assessment_id:
//Creating a new user in which every field is null/null object.
Assessment_Information user=new Assessment_Information();
Intent iChange=new Intent(assessment_table_edit.this,assessment_edit_data.class);
Bundle b=new Bundle();
//Passing an a field from the null object.
b.putString("stuID",user.getStuID());
iChange.putExtras(b);
// iChange.putExtra("stuID",user.getStuID());
startActivity(iChange);
break;
}
}
};
Try MarcGV's answer, or some variation of it to get some data.
I am loading list in ListView using AsyncTask by showing ProgressBar. But in my code the ProgressBar is now showing. Cant understand the problem.
I used the same code as in slidenerd but in the video code works but my code doesn't seem to work.
Video Link
public class MainActivity extends AppCompatActivity {
ListView listView;
String[] items = {"Ankush", "Kapoor", "Amit", "Kumar", "Shirshak", "Tillu", "Mishra", "Sudeep", "Dey", "Ayon",
"Ankush", "Kapoor", "Amit", "Kumar", "Shirshak", "Tillu", "Mishra", "Sudeep", "Dey", "Ayon",
"Ankush", "Kapoor", "Amit", "Kumar", "Shirshak", "Tillu", "Mishra", "Sudeep", "Dey", "Ayon",
"Ankush", "Kapoor", "Amit", "Kumar", "Shirshak", "Tillu", "Mishra", "Sudeep", "Dey", "Ayon"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
requestWindowFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new ArrayList<String>());
listView.setAdapter(adapter);
new JSONTask().execute();
}
public class JSONTask extends AsyncTask<Void, String, Void> {
private ArrayAdapter<String> adapter;
private int count = 0;
#Override
protected void onPreExecute() {
adapter = (ArrayAdapter<String>) listView.getAdapter();
setProgressBarIndeterminateVisibility(true);
setProgressBarVisibility(true);
}
#Override
protected Void doInBackground(Void... params) {
for (String i : items) {
publishProgress(i);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
adapter.add(values[0]);
count++;
setProgress((int) (((double) count / items.length) * 10000));
}
#Override
protected void onPostExecute(Void aVoid) {
setProgressBarIndeterminateVisibility(false);
setProgressBarVisibility(false);
Toast.makeText(getApplicationContext(), "Done!", Toast.LENGTH_SHORT).show();
}
}
}
From the documentation of setProgressBarVisibility() and setProgressBarIndeterminateVisibility():
This method was deprecated in API level 24.
No longer supported
starting in API 21.
You should use a ProgressDialog instead.
you should use simple ProgressDialog
for example :
ProgressDialog myPd = ProgressDialog.show(context, "Please wait", "Uploading Database to Cloud...", true);
myPd.setCancelable(false);
I am fetching data from json with Volley and populating RecyclerView with the parsed data but I ran into a bit of problem:
The call to get the items is in onCreate method, so the call is repeated each time the activity is recreated both from configuration changes and otherwise; hence the data is reloaded. So I found this answer that uses parcelables
and this article on Codepath (still on parcelables). After I have followed the instructions explicitly (or so I feel), there seems to be no change: the call to get data is repeated each time the activity is recreated.
FruitItems
public class FruitItems implements Parcelable {
private String fruit_title;
private String fruit_description;
private String fruit_image;
public String getFruit_title() {
return fruit_title;
}
public void setFruit_title(String fruit_title) {
this.fruit_title = fruit_title;
}
public String getFruit_description() {
return fruit_description;
}
public void setFruit_description(String fruit_description) {
this.fruit_description = fruit_description;
}
public String getFruit_image() {
return fruit_image;
}
public void setFruit_image(String fruit_image) {
this.fruit_image = fruit_image;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.fruit_title);
dest.writeString(this.fruit_description);
dest.writeString(this.fruit_image);
}
public FruitItems() {
}
protected FruitItems(Parcel in) {
this.fruit_title = in.readString();
this.fruit_description = in.readString();
this.fruit_image = in.readString();
}
public static final Parcelable.Creator<FruitItems> CREATOR = new Parcelable.Creator<FruitItems>() {
#Override
public FruitItems createFromParcel(Parcel source) {
return new FruitItems(source);
}
#Override
public FruitItems[] newArray(int size) {
return new FruitItems[size];
}
};
}
MainActivity
public class MainActivity extends AppCompatActivity {
private final String TAG = "MainActivity";
private final String KEY_POST_ITEMS = "fruititems";
//List of fruits
private List<FruitItems> mFruitItemsList;
//Views
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate called");
//Initializing Views
recyclerView = (RecyclerView) findViewById(R.id.fruit_recycler);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
if (savedInstanceState != null && savedInstanceState.containsKey(KEY_POST_ITEMS)) {
mFruitItemsList = savedInstanceState.getParcelableArrayList(KEY_POST_ITEMS);
} else {
//Initializing the fruitlist
mFruitItemsList = new ArrayList<>();
if (NetworkCheck.isAvailableAndConnected(this)) {
getData();
} else {
final Context mContext;
mContext = this;
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle(R.string.alert_titl);
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setIcon(R.mipmap.ic_launcher);
alertDialogBuilder.setMessage(R.string.alert_mess);
alertDialogBuilder.setPositiveButton(R.string.alert_retry, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (!NetworkCheck.isAvailableAndConnected(mContext)) {
alertDialogBuilder.show();
} else {
getData();
}
}
});
alertDialogBuilder.setNegativeButton(R.string.alert_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialogBuilder.show();
}
}
adapter = new FruitAdapter(mFruitItemsList, this);
recyclerView.setAdapter(adapter);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putParcelableArrayList(KEY_POST_ITEMS, ArrayList<? extends Parcelable>))mFruitItemsList);
super.onSaveInstanceState(savedInstanceState);
}
//Getting json data
private void getData(){
Log.d(TAG, "getData called");
//Show progress dialog
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setCancelable(false);
mProgressDialog.setMessage(this.getResources().getString(R.string.load_fruit));
mProgressDialog.show();
//Creating a json request
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigFruit.GET_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "onResponse called");
//Dismissing the progress dialog
if (mProgressDialog != null) {
mProgressDialog.hide();
}
//calling method to parse json array
parseData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(jsonArrayRequest);
}
//parsing json data
private void parseData(JSONArray array){
Log.d(TAG, "Parsing array");
for(int i = 0; i<array.length(); i++) {
FruitItems fruitItem = new FruitItems();
JSONObject jsonObject = null;
try {
jsonObject = array.getJSONObject(i);
fruitItem.setFruit_title(jsonObject.getString(ConfigFruit.TAG_POST_TITLE));
fruitItem.setFruit_description(jsonObject.getString(ConfigFruit.TAG_POST_DESCRIPTION));
//Parsing image
JSONObject fruitImage = jsonObject.getJSONObject("thumbnail");
fruitItem.setFruit_image(fruitImage.getString("url"));
} catch (JSONException w) {
w.printStackTrace()
}
mFruitItemsList.add(fruitItem);
}
adapter.notifyItemRangeChanged(0, adapter.getItemCount());
}
}
I may not be a pro but I know that I have goofed somewhere in the codes above, else it should have worked.
Now, my question is where did I goof and how do I plug this mistake?
EDIT
I have edited the codes above to reflect the answer that I accepted. It works fine but there is still a problem.
I start Activity B from MainActivity. If I press the back-button in Activity B the data is saved but when I press the up-button, the getData is called again and the data is re-fetched.
Please, is there anyway around this?
You don't seem to have an onSaveInstanceState in your mainactivity. You need something like
#Override
protected void onSaveInstanceState (Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList(KEY_POST_ITEMS,mFruitItemsList) ;
}
In order to retain your data for the activity that is about to be destructed and the one that is being created, you need to override the onSaveInstance callback
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putParcelableArrayList(KEY_POST_ITEMS, (ArrayList)mFruitItemsList);
super.onSaveInstanceState(savedInstanceState);
}
NOTE: always remember to call the superclass.
First of all, I am relatively new to android programming.
I am creating a ViewPager application with two Fragments. One of the Fragments requests data from a server and return a result to the main FragmentActivity. My problem is that this request to the server can take sometime, and I have been trying to get a ProgressDialog to appear with AsyncTask while the user waits for the data to be retrieved. Once I create the background thread to retrieve the data, I successfully execute some code in the onPostExecute() method and set some variables. However, the return statement that sends information back to the FragmentActivity is being executed before the background thread actually ends. I can't seem to figure out a way for the main thread to wait on the background thread. Using Asyctask's get() method results in the ProgressDialog from appearing. I have looked through a lot of posts in here, but can't seem to find an answer.
Anything helps.
Code below:
SplashScreen.java
public class SplashScreen extends FragmentActivity {
MainMenu mainMenu;
MapScreen mapScreen;
PagerAdapter pagerAdapter;
ViewPager viewPager;
List<LatLng> geoPoints;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash_screen);
context = this;
initializePaging();
}
private void initializePaging()
{
mainMenu = new MainMenu();
mapScreen = new MapScreen();
pagerAdapter = new PagerAdapter(getSupportFragmentManager());
pagerAdapter.addFragment(mainMenu);
pagerAdapter.addFragment(mapScreen);
viewPager = (ViewPager) super.findViewById(R.id.viewPager);
viewPager.setAdapter(pagerAdapter);
viewPager.setOffscreenPageLimit(2);
viewPager.setCurrentItem(0);
viewPager.setOnPageChangeListener(new OnPageChangeListener()
{
#Override
public void onPageScrollStateChanged(int postion){}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2){}
#Override
public void onPageSelected(int position)
{
switch(position){
case 0: findViewById(R.id.first_tab).setVisibility(View.VISIBLE);
findViewById(R.id.second_tab).setVisibility(View.INVISIBLE);
break;
case 1: findViewById(R.id.first_tab).setVisibility(View.INVISIBLE);
findViewById(R.id.second_tab).setVisibility(View.VISIBLE);
break;
}
}
});
}
//Called from onClick in main_mainu.xml
public void getDirections(View view)
{
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
try
{
geoPoints = mainMenu.getDirections(context);
mapScreen.plotPoints(geoPoints);
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Error! Invalid address entered.", Toast.LENGTH_LONG).show();
mainMenu.clear();
}
}
}
MainMenu.java
public class MainMenu extends Fragment {
String testString;
int testInt;
TextView testTV;
private TextView tvDisplay;
private EditText departure;
private EditText destination;
private Geocoder geocoder;
private List<Address> departAddress;
private List<Address> destinationAddress;
private List<LatLng> geoPoints;
private String departString;
private String destinationString;
private Address departLocation;
private Address destinationLocation;
private LatLng departurePoint;
private LatLng destinationPoint;
private Context contextMain;
private GetData task;
public MainMenu()
{
super();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View root = (View) inflater.inflate(R.layout.main_menu, null);
geoPoints = new ArrayList<LatLng>(2);
return root;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
departure = (EditText) getView().findViewById(R.id.depart_field);
destination = (EditText) getView().findViewById(R.id.destination_field);
tvDisplay = (TextView) getView().findViewById(R.id.textView1);
}
public List<LatLng> getDirections(Context context)
{
contextMain = context;
geocoder = new Geocoder(getActivity());
departString = departure.getText().toString();
destinationString = destination.getText().toString();
try
{
task = new GetData(new Callback(){
public void run(Object result)
{
//return geoPoints;
}
});
task.execute((Void[])null);
}catch(Exception e)
{
e.printStackTrace();
}
return geoPoints;
}
public void clear()
{
departure.setText("");
destination.setText("");
tvDisplay.setText("Enter departure point, and destination point");
}
private class GetData extends AsyncTask<Void, Void, List<List<Address>>>
{
Callback callback;
private ProgressDialog processing;
public GetData(Callback callback)
{
this.callback = callback;
}
#Override
protected void onPreExecute()
{
processing = new ProgressDialog(contextMain);
processing.setTitle("Processing...");
processing.setMessage("Please wait.");
processing.setCancelable(false);
processing.setIndeterminate(true);
processing.show();
}
#Override
protected List<List<Address>> doInBackground(Void...arg0)
{
List<List<Address>> list = new ArrayList<List<Address>>(2);
try
{
departAddress = geocoder.getFromLocationName(departString, 5, 37.357059, -123.035889, 38.414862, -121.723022);
destinationAddress = geocoder.getFromLocationName(destinationString, 5, 37.357059, -123.035889, 38.414862, -121.723022);
list.add(departAddress);
list.add(destinationAddress);
}catch(IOException e)
{
e.printStackTrace();
}
return list;
}
#Override
protected void onPostExecute(List<List<Address>> list)
{
departLocation = list.get(0).get(0);
destinationLocation = list.get(1).get(0);
departurePoint = new LatLng(departLocation.getLatitude(), departLocation.getLongitude());
destinationPoint = new LatLng(destinationLocation.getLatitude(), destinationLocation.getLongitude());
if(geoPoints.size() >= 2)
{
geoPoints.clear();
}
geoPoints.add(departurePoint);
geoPoints.add(destinationPoint);
callback.run(list);
processing.dismiss();
}
}
}
#Override
protected Object doInBackground(Void...arg0)
{
Object result = null;
try
{
departAddress = geocoder.getFromLocationName(departString, 5, 37.357059, -123.035889, 38.414862, -121.723022);
destinationAddress = geocoder.getFromLocationName(destinationString, 5, 37.357059, -123.035889, 38.414862, -121.723022);
}catch(IOException e)
{
e.printStackTrace();
}
return result;
}
You never set the value of result...
My layout has 13 TextViews which on click changes the ListView Items.
Here is my activity:
public class ExampleActivity extends ListActivity implements
OnClickListener {
private String[] sa = new String[100];
private ListView lv;
private Context context = this;
private ArrayAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new LongOperation().execute("1");
lv = getListView();
}
private class LongOperation extends AsyncTask<String, Void, String> {
private ProgressDialog dialog = new ProgressDialog(
ExampleActivity.this);
#Override
protected String doInBackground(String... params) {
int i = Integer.parseInt(params[0]);
for (int n = 0; n < 100; n++) {
if (i != 5 && i != 10) {
sa[n] = "Item" + i;
} else {
}
}
return params[0];
}
#Override
protected void onPostExecute(String result) {
adapter = new ArrayAdapter<Object>(context,
android.R.layout.simple_list_item_1, sa);
lv.setAdapter(adapter);
this.dialog.dismiss();
}
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
public void onClick(View v) {
Log.d("onClick", v.getId() + "**");
int id = v.getId();
switch (id) {
case R.id.tv1: {
new LongOperation().execute("1");
}
case R.id.tv2: {
new LongOperation().execute("2");
}
case R.id.tv3: {
new LongOperation().execute("3");
}
case R.id.tv4: {
new LongOperation().execute("4");
}
case R.id.tv5: {
new LongOperation().execute("5");
}
case R.id.tv6: {
new LongOperation().execute("6");
}
case R.id.tv7: {
new LongOperation().execute("7");
}
case R.id.tv8: {
new LongOperation().execute("8");
}
case R.id.tv9: {
new LongOperation().execute("9");
}
case R.id.tv10: {
new LongOperation().execute("10");
}
case R.id.tv11: {
new LongOperation().execute("11");
}
case R.id.tv12: {
new LongOperation().execute("12");
}
case R.id.tv13: {
new LongOperation().execute("13");
}
}
}
}
the listView is populated as item1 when i launch the app. but when i click on any of the TextViews, the onClick method is not triggered. i checked it using a Log.
Thank You.
Because you are not registering onClickListener with your TextViews hence your TextViews are not getting Clicked event.
For this you have to do something like,
onCreate()
{
TextView tv1 = (TextVIew)findViewById(R.id.tv1);
tv1.setOnClickListener(this);
Better Solution:
In your Activity's xml Layout File,
in your all TextView put attribute android:onClick="textClick"
Now remove onClickListener from your Activity and just write
public void textClick(View TextView)
in your activity. Then you don't have to register onClicklistener for all TextView. Android does itself for you..
This is a sample program provided when you use implements OnClickListener
public class ExampleActivity extends Activity implements OnClickListener {
protected void onCreate(Bundle savedValues) {
Button button = (Button)findViewById(R.id.corky);
button.setOnClickListener(this); // have a look on this line. registering.
}
// Implement the OnClickListener callback
public void onClick(View v) {
// do something when the button is clicked
}
}
this happens because you not using the setOnClickListener() for your TextViews
Add this static function in your activity class, This work for me in my MainActivity.java
public class MainActivity extends AppCompatActivity {
static {
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}