My app was working perfectly until I added the airpush SDK. Now when I run it and try to use it, I get these errors and the app shuts down:
App code:
package com.etqanapps.EtqanChannel.UI;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.MyChannel.R;
import com.etqanapps.EtqanChannel.Adapters.PlayListAdapterSliding;
import com.etqanapps.EtqanChannel.Controllers.Consts;
import com.etqanapps.EtqanChannel.DataModel.PlayListModel;
import com.etqanapps.EtqanChannel.DataModel.VideoModel;
import com.etqanapps.EtqanChannel.Listeners.MenuActionsListener;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
public class UIPlayList extends RelativeLayout implements OnItemClickListener,
OnClickListener {
ListView lv;
TextView tv_title;
Button btn_open_menu;
Button btn_open_info;
ArrayList<VideoModel> feed;
Context c;
PlayListAdapterSliding ad;
MenuActionsListener listener;
Activity ac;
AdView ad1;
AdView ad2;
String AD_UNIT_ID;
public UIPlayList(Context context, MenuActionsListener listener,Activity ac) {
super(context);
feed = new ArrayList<VideoModel>();
this.listener = listener;
c = context;
this.ac=ac;
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater) getContext().getSystemService(
inflater);
if(isTablet(c)){
if(Consts.isEnglish()){
li.inflate(R.layout.ui_play_list_tab, this, true);
}else{
li.inflate(R.layout.ui_play_list_tab_ar, this, true);
}
}else{
if(Consts.isEnglish()){
li.inflate(R.layout.ui_play_list_phone, this, true);
}else{
li.inflate(R.layout.ui_play_list_phone_ar, this, true);
}
}
lv = (ListView) findViewById(R.id.lv);
tv_title = (TextView) findViewById(R.id.tv_title);
btn_open_menu = (Button) findViewById(R.id.btn_open_menu);
btn_open_info = (Button) findViewById(R.id.btn_open_info);
btn_open_menu.setOnClickListener(this);
btn_open_info.setOnClickListener(this);
AD_UNIT_ID=c.getString(R.string.AD_UNIT_ID);
if(AD_UNIT_ID.length()>1){
initAds();
}
lv.setAdapter(ad);
}
private void initAds() {
ad1=new AdView(ac, AdSize.SMART_BANNER,AD_UNIT_ID);
ad2=new AdView(ac, AdSize.SMART_BANNER,AD_UNIT_ID);
lv.addHeaderView(ad1);
lv.addFooterView(ad2);
reLoadAds();
}
public void reLoadAds() {
ad1.loadAd(new AdRequest());
ad2.loadAd(new AdRequest());
}
public UIPlayList refreshData(PlayListModel pl) {
feed.clear();
feed.addAll(0, pl.getVideos());
if (isTablet(c)) {
if(Consts.isEnglish()){
ad = new PlayListAdapterSliding(c, R.layout.row_video_tab, feed,ac);
}else{
ad = new PlayListAdapterSliding(c, R.layout.row_video_tab_ar, feed,ac);
}
} else {
if(Consts.isEnglish()){
ad = new PlayListAdapterSliding(c, R.layout.row_video_phone, feed,ac);
}else{
ad = new PlayListAdapterSliding(c, R.layout.row_video_phone_ar, feed,ac);
}
}
tv_title.setText(pl.getTitle());
lv.setAdapter(ad);
lv.setOnItemClickListener(this);
ad.notifyDataSetChanged();
if(ad1!=null){
reLoadAds();
}
return this;
}
public static boolean isTablet(Context c) {
DisplayMetrics displayMetrics = c.getResources().getDisplayMetrics();
int width = displayMetrics.widthPixels / displayMetrics.densityDpi;
int height = displayMetrics.heightPixels / displayMetrics.densityDpi;
double screenDiagonal = Math.sqrt(width * width + height * height);
System.out.println("screenDiagonal : " + screenDiagonal);
return (screenDiagonal >= 6.0);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {
VideoModel video = feed.get(index-1);
listener.onOpenVideo(video);
}
#Override
public void onClick(View v) {
if (v == btn_open_info) {
listener.openInfo();
}else if (v == btn_open_menu) {
listener.showMenu();
}
}
}
According to your logcat, you are getting ArrayIndexOutOfBoundsException in onItemClick(). This is because you are subtracting 1 from the zero-based position of the AdapterView and so if the index is 0 you get -1 which obviously is outside the bounds of your Array.
Change that to just use the index.
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {
VideoModel video = feed.get(index); // Here
Alternatively,
Just now i noticed your code, You haven't imported any Airpush SDK Class's instead i could see Admob SDK imported syntax's.
Related
hello guys i started to learn to build android applications via udacy. After a long troubleshooting i didnt find something that can cause the bug that i have. the bug is that when i rotate the phone the view seems to clone it self and not deleting the previous one if someone can help me ill be very happy.
1) normal state of app:
2) after rotation:
3) and after another rotation the application crashing
it never happend until i added the code in the xml file of the view:
<?xml version="1.0" encoding="utf-8"?>
<!-- Layout for weather forecast list item for future day (not today) -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeight"
android:orientation="horizontal"
android:padding="16dp">
<ImageView
android:id="#+id/list_item_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/ic_launcher"/>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
android:orientation="vertical"
android:paddingLeft="16dp">
<TextView
android:id="#+id/list_item_date_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tomorrow"/>
<TextView
android:id="#+id/list_item_forecast_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="1"
android:gravity="right">
<TextView
android:id="#+id/list_item_high_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="81"
android:paddingLeft="10dp"/>
<TextView
android:id="#+id/list_item_low_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="68"
android:paddingLeft="10dp"/>
</LinearLayout>
</LinearLayout>
Activity Code:
package com.example.andy.sunshine.app;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
private String FORECASTFRAGMENT_TAG = "FFTAG";
String mLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment, new MainActivityFragment(), FORECASTFRAGMENT_TAG)
.commit();
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mLocation = Utility.getPreferredLocation(this);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
protected void onResume() {
super.onResume();
String location = Utility.getPreferredLocation(this);
if(location != null && location != mLocation){
MainActivityFragment ff = (MainActivityFragment)getSupportFragmentManager().findFragmentById(R.id.fragment);
if(ff != null){
ff.onLocationChanged();
}
mLocation = location;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if(id == R.id.action_settings){
Intent settings = new Intent(this,SettingsActivity.class);
startActivity(settings);
}
if(R.id.action_map == id){
openPreferedLocationMap();
}
return super.onOptionsItemSelected(item);
}
private void openPreferedLocationMap(){
String location = Utility.getPreferredLocation(this);
Uri geoLocation = Uri.parse("geo:0,0?").buildUpon().appendQueryParameter("q",location).build();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(geoLocation);
if(intent.resolveActivity(getPackageManager()) != null){
startActivity(intent);
}
else{
Log.d("SHOWING MAP PROBLEMM","could't call"+ location+ "intent");
}
}
}
Fragment Code:
package com.example.andy.sunshine.app;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.example.andy.sunshine.app.data.WeatherContract;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* A placeholder fragment containing a simple view.
*/
public class MainActivityFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
private static final int FORECAST_LOADER = 0;
// For the forecast view we're showing only a small subset of the stored data.
// Specify the columns we need.
private static final String[] FORECAST_COLUMNS = {
// In this case the id needs to be fully qualified with a table name, since
// the content provider joins the location & weather tables in the background
// (both have an _id column)
// On the one hand, that's annoying. On the other, you can search the weather table
// using the location set by the user, which is only in the Location table.
// So the convenience is worth it.
WeatherContract.WeatherEntry.TABLE_NAME + "." + WeatherContract.WeatherEntry._ID,
WeatherContract.WeatherEntry.COLUMN_DATE,
WeatherContract.WeatherEntry.COLUMN_SHORT_DESC,
WeatherContract.WeatherEntry.COLUMN_MAX_TEMP,
WeatherContract.WeatherEntry.COLUMN_MIN_TEMP,
WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING,
WeatherContract.WeatherEntry.COLUMN_WEATHER_ID,
WeatherContract.LocationEntry.COLUMN_COORD_LAT,
WeatherContract.LocationEntry.COLUMN_COORD_LONG
};
// These indices are tied to FORECAST_COLUMNS. If FORECAST_COLUMNS changes, these
// must change.
static final int COL_WEATHER_ID = 0;
static final int COL_WEATHER_DATE = 1;
static final int COL_WEATHER_DESC = 2;
static final int COL_WEATHER_MAX_TEMP = 3;
static final int COL_WEATHER_MIN_TEMP = 4;
static final int COL_LOCATION_SETTING = 5;
static final int COL_WEATHER_CONDITION_ID = 6;
static final int COL_COORD_LAT = 7;
static final int COL_COORD_LONG = 8;
private ForecastAdapter mForecastAdapter;
public MainActivityFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add this line in order for this fragment to handle menu events.
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.forecastfragment, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_refresh) {
updateWeather();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// The CursorAdapter will take data from our cursor and populate the ListView.
mForecastAdapter = new ForecastAdapter(getActivity(), null, 0);
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// Get a reference to the ListView, and attach this adapter to it.
ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView adapterView, View view, int position, long l) {
// CursorAdapter returns a cursor at the correct position for getItem(), or null
// if it cannot seek to that position.
Cursor cursor = (Cursor) adapterView.getItemAtPosition(position);
if (cursor != null) {
String locationSetting = Utility.getPreferredLocation(getActivity());
Intent intent = new Intent(getActivity(), DetailActivity.class)
.setData(WeatherContract.WeatherEntry.buildWeatherLocationWithDate(
locationSetting, cursor.getLong(COL_WEATHER_DATE)
));
startActivity(intent);
}
}
});
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
getLoaderManager().initLoader(FORECAST_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
private void updateWeather() {
FetchWeatherTask weatherTask = new FetchWeatherTask(getActivity());
String location = Utility.getPreferredLocation(getActivity());
weatherTask.execute(location);
}
public void onLocationChanged(){
updateWeather();
getLoaderManager().restartLoader(FORECAST_LOADER,null,this);
}
#Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
String locationSetting = Utility.getPreferredLocation(getActivity());
// Sort order: Ascending, by date.
String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATE + " ASC";
Uri weatherForLocationUri = WeatherContract.WeatherEntry.buildWeatherLocationWithStartDate(
locationSetting, System.currentTimeMillis());
return new CursorLoader(getActivity(),
weatherForLocationUri,
FORECAST_COLUMNS,
null,
null,
sortOrder);
}
#Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
mForecastAdapter.swapCursor(cursor);
}
#Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
mForecastAdapter.swapCursor(null);
}
}
And Class That Extends CursorAdapter "ForecastAdapter":
package com.example.andy.sunshine.app;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.andy.sunshine.app.data.WeatherContract;
/**
* {#link ForecastAdapter} exposes a list of weather forecasts
* from a {#link android.database.Cursor} to a {#link android.widget.ListView}.
*/
public class ForecastAdapter extends CursorAdapter {
private final int VIEW_TYPE_TODAY = 0;
private final int VIEW_TYPE_FUTURE_DAY = 1;
public ForecastAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
}
#Override
public int getItemViewType(int position) {
return (position == 0)? VIEW_TYPE_TODAY:VIEW_TYPE_FUTURE_DAY;
}
#Override
public int getViewTypeCount() {
return 2;
}
/**
* Prepare the weather high/lows for presentation.
*/
private String formatHighLows(Context context,double high, double low) {
boolean isMetric = Utility.isMetric(mContext);
String highLowStr = Utility.formatTemperature(context,high, isMetric) + "/" + Utility.formatTemperature(context,low, isMetric);
return highLowStr;
}
/*
This is ported from FetchWeatherTask --- but now we go straight from the cursor to the
string.
*/
private String convertCursorRowToUXFormat(Context context,Cursor cursor) {
// get row indices for our cursor
String highAndLow = formatHighLows(context,
cursor.getDouble(MainActivityFragment.COL_WEATHER_MAX_TEMP),
cursor.getDouble(MainActivityFragment.COL_WEATHER_MAX_TEMP));
return Utility.formatDate(cursor.getLong(MainActivityFragment.COL_WEATHER_DATE)) +
" - " + cursor.getString(MainActivityFragment.COL_WEATHER_DESC) +
" - " + highAndLow;
}
/*
Remember that these views are reused as needed.
*/
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
int VIEW_TYPE = getItemViewType(cursor.getPosition());
int layoutId = -1;
if(VIEW_TYPE == VIEW_TYPE_TODAY){
layoutId = R.layout.list_item_forecast_today;
}else if(VIEW_TYPE == VIEW_TYPE_FUTURE_DAY){
layoutId = R.layout.list_item_forecast;
}
View view = LayoutInflater.from(context).inflate(layoutId, parent, false);
MyViewHolder viewHolder = new MyViewHolder(view);
view.setTag(viewHolder);
return view;
}
/*
This is where we fill-in the views with the contents of the cursor.
*/
#Override
public void bindView(View view, Context context, Cursor cursor) {
// our view is pretty simple here --- just a text view
// we'll keep the UI functional with a simple (and slow!) binding.
MyViewHolder viewHolder = (MyViewHolder)view.getTag();
viewHolder.iconView.setImageResource(R.mipmap.ic_launcher);
// TODO Read date from cursor
long dateInMillis = cursor.getLong(MainActivityFragment.COL_WEATHER_DATE);
viewHolder.dateView.setText(Utility.getFriendlyDayString(context, dateInMillis));
// TODO Read weather forecast from cursor
viewHolder.descriptionView.setText(cursor.getString(MainActivityFragment.COL_WEATHER_DESC));
// Read user preference for metric or imperial temperature units
boolean isMetric = Utility.isMetric(context);
// Read high temperature from cursor
double high = cursor.getDouble(MainActivityFragment.COL_WEATHER_MAX_TEMP);
viewHolder.highTempView.setText(Utility.formatTemperature(context,high, isMetric));
// TODO Read low temperature from cursor
double low = cursor.getDouble(MainActivityFragment.COL_WEATHER_MIN_TEMP);
viewHolder.lowTempView.setText(Utility.formatTemperature(context,low, isMetric));
}
public static class MyViewHolder {
public final ImageView iconView;
public final TextView dateView;
public final TextView descriptionView;
public final TextView highTempView;
public final TextView lowTempView;
public MyViewHolder(View view){
iconView = (ImageView) view.findViewById(R.id.list_item_icon);
dateView = (TextView)view.findViewById(R.id.list_item_date_textview);
descriptionView = (TextView)view.findViewById(R.id.list_item_forecast_textview);
highTempView = (TextView)view.findViewById(R.id.list_item_high_textview);
lowTempView = (TextView)view.findViewById(R.id.list_item_low_textview);
}
}
}
if you want to see the whole project and check maybe for errors that may cause that i posting here my github https://github.com/obruchkov/Sunshine with all the code that i did. please help me guys
i want to create ids for three buttons so that i can use them in a switch case i want the ids to be unique in each loop like btna[1].setid("btna"+1),btnb[1].setid("btnb"+1),btnc[3].setid("btnc"+3) somethimg like that and i want to repet this for n number of times
here is my code:
package com.astro.famouspandit.Activities.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.astro.famouspandit.Database.DatabaseHelper;
import com.astro.famouspandit.R;
import com.astro.famouspandit.datasets.ItemProfile;
import java.util.ArrayList;
import mehdi.sakout.fancybuttons.FancyButton;
public class ProfleList extends AppCompatActivity implements View.OnClickListener{
private TextView txtProfileName,txtProfileDate,txtProfileTime,txtProfileLocation;
private FancyButton btnEdit[],btnDelete[],btnView[];
LinearLayout linearlist ;
DatabaseHelper mydb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profle_list);
mydb = new DatabaseHelper(this);
long count = mydb.getCount();
Log.d("count", "onCreate: "+count);
if (count == 0){
}else{
ArrayList<ItemProfile> listprofile = mydb.profilelist();
for (int i = 1; i < count+1; i++ ) {
ItemProfile itemProfile = listprofile.get(i-1);
linearlist = (LinearLayout)findViewById(R.id.layoutlist);
View[] myView = new View[i];
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
myView[i-1] = inflater.inflate(R.layout.profile_list, null);
txtProfileName = (TextView)myView[i-1].findViewById(R.id.txtName);
txtProfileDate = (TextView)myView[i-1].findViewById(R.id.txtDate);
txtProfileTime = (TextView)myView[i-1].findViewById(R.id.txtTime);
txtProfileLocation = (TextView)myView[i-1].findViewById(R.id.txtLocation);
btnEdit[i] = (FancyButton)myView[i-1].findViewById(R.id.btn_edtProfile);
btnDelete[i] = (FancyButton)myView[i-1].findViewById(R.id.btn_deleteProfile);
btnView[i] = (FancyButton)myView[i-1].findViewById(R.id.btn_viewProfile);
btnEdit[i].setOnClickListener(this);
btnDelete[i].setOnClickListener(this);
btnDelete[i].setOnClickListener(this);
String profileName = itemProfile.getProfileName();
txtProfileName.setText(profileName);
Log.d("ProfileName", "onCreate: "+itemProfile.getProfileName());
int dd = itemProfile.getDay();
int mm = itemProfile.getMonth();
int yy = itemProfile.getYear();
txtProfileDate.setText(dd+"/"+mm+"/"+yy);
Log.d("Profiledate", "onCreate: "+itemProfile.getDay()+itemProfile.getMonth()+itemProfile.getYear());
int hour = itemProfile.getHour();
int min = itemProfile.getMinute();
txtProfileTime.setText(hour+":"+min);
Log.d("ProfileTime", "onCreate: "+itemProfile.getHour()+itemProfile.getHour());
String city = itemProfile.getCity();
txtProfileLocation.setText(itemProfile.getCity());
Log.d("citylocation,city", "onCreate: "+itemProfile.getCity()+","+city);
linearlist.addView(myView[i-1]);
}
}
}
#Override
public void onClick(View v) {
}
}
I recommend using View.setTag(), where you can set an object to a View.
View also has a method called findViewWithTag(Object tag) where it searches between the child views for the given tag (using Object.equals()).
So to adapt it to your case:
btna[1].setTag("btna" + 1);
btnb[1].setTag("btnb" + 1);
btnc[3].setTag("btnc" + 3);
You can easily make a for loop from this.
And then later:
Button btnc = (Button)container.findViewWithTag("btnc3");
Just make sure that the buttons are direct children of the ViewGroup named container.
To handle click events, modify your onClick() this way:
#Override
public void onClick(View v) {
String tag = v.getTag();
if (tag.equals("btna1")) {
Log.i("Test", "Clicked on button A 1");
} else if (tag.equals("btnb1")) {
Log.i("Test", "Clicked on button B 1");
}
}
And so on...
You can use switch-case with Strings only in Java 7, which is available from ADT 22.6.
I'm Getting data from my database and pushing them into ListView to view all the data.
Inside my ListView I also have a TextView with the text "Like" in it. Now when I click the like text it will change to "Liked" and I'm updating my like status in my database.
Now my problem is that when i click the "Like" text, the text changes to "Liked" and also it is updated in DB. But also when I scroll through the List View, I can notice other lists' Like text is also changed to Liked. I'm not sure what's going wrong.
I've been trying to get around this problem for quite some days but had no success.
This is my adapter code. At the bottom you can see my onClickListener for the textview
package com.mytestapp.myapp;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ForumAdapter extends ArrayAdapter<DiscussionList> {
private static List<DiscussionList> items = null;
public ForumAdapter(Context context, List<DiscussionList> items) {
super(context, R.layout.custom_list, items);
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
public static DiscussionList getModelPosition(int position) {
return items.get(position);
}
public void refill(List<DiscussionList> items) {
items.clear();
items.addAll(items);
notifyDataSetChanged();
}
public static class ViewHolder {
WebView mywebviewholder;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View v = convertView;
if (v == null) {
LayoutInflater li = LayoutInflater.from(getContext());
v = li.inflate(R.layout.custom_list, null);
} else {
holder = (ViewHolder) convertView.getTag();
}
DiscussionList app = items.get(position);
if (app != null) {
TextView titleText = (TextView) v.findViewById(R.id.dscTitle);
TextView categoryText = (TextView) v.findViewById(R.id.dscCategory);
TextView descriptionText = (TextView) v
.findViewById(R.id.dscDescription);
TextView timeText = (TextView) v.findViewById(R.id.dscTime);
TextView idText = (TextView) v.findViewById(R.id.dscDiscId);
final TextView likeText = (TextView) v.findViewById(R.id.likeText1);
String like_Status = app.getLikeStatus();
titleText.setText(app.getTitle());
categoryText.setText(app.getCategory());
descriptionText.setText(app.getDescription());
timeText.setText(app.getTime());
idText.setText(app.getDiscId());
if (like_Status == "null") {
likeText.setText("Like");
} else {
likeText.setText("Liked");
}
final String dId = app.getDiscId();
// onClick for image button inside list view
likeText.setTag(new Integer(position));
likeText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Integer myposition = (Integer) view.getTag();
// Toast.makeText(getContext(), "" + dId,
// Toast.LENGTH_SHORT)
// .show();
likeText.setText("Liked");
MainActivity val = new MainActivity();
val.updateLikeTable(dId);
}
});
}
return v;
}
}
And also this is my MainActivity.java file where i update the likes in database
package com.mytestapp.myapp;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity implements FetchDataListener {
public static String strTitle = "0", strCategory = "0",
strDescription = "0", strTime = "0", strDid = "0";
Collegemate_DB db = new Collegemate_DB(this);
int likeStatus = 1;
private ProgressDialog dialog;
public static String usId=null;
ImageButton imgButton;
List<DiscussionList> items = new ArrayList<DiscussionList>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_forum_topics);
usId = db.getCurrentuserId();
initView();
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
/*
* On click listener to get values from DiscussionList class and send it
* to another activity when clicking on the list item
*/
ListView forumList = getListView();
forumList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Get position of the clicked list item from adapter
String dTitle, dCategory, dDescription, dTime, dDid;
DiscussionList accessVar = ForumAdapter
.getModelPosition(position);
dTitle = accessVar.getTitle();
dCategory = accessVar.getCategory();
dDescription = accessVar.getDescription();
dTime = accessVar.getTime();
dDid = accessVar.getDiscId();
/*
* Storing the forum values in string and passing it to another
* activity
*/
String values[] = { dTitle, dCategory, dDescription, dTime,
dDid };
Intent i = new Intent(MainActivity.this, ForumFullView.class);
i.putExtra("sendData", values);
startActivity(i);
}
});
}
private void initView() {
// show progress dialog
Log.i("j","Inside Init");
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "http://example.com/mypath/listData.php?currentUser_id="
+ usId;
Log.i("Fetch Url : ", url);
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
#Override
public void onFetchComplete(List<DiscussionList> data) {
// dismiss the progress dialog
if (dialog != null)
dialog.dismiss();
// create new adapter
ListView forumList = getListView();
// set the adapter to list
ForumAdapter adapter = new ForumAdapter(this, data);
if (forumList.getAdapter() == null) {
//final ForumAdapter adapter = new ForumAdapter(this, data);
forumList.setAdapter(adapter);
} else {
((ForumAdapter) forumList.getAdapter()).refill(items);
}
// setListAdapter(adapter);
}
#Override
public void onFetchFailure(String msg) {
// dismiss the progress dialog
if (dialog != null)
dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
public void updateLikeTable(String dId,List<DiscussionList> items) {
try {
String likeUrl = "http://example.com/mypath/createlike.php?discId="
+ dId + "&userId=" + usId + "&like_status=" + likeStatus;
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(likeUrl));
client.execute(request);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Any help is appreciated.
Thanks in advance
The problem you're having is that the ListView widget recycles its views if it can. Once a view is off the screen from scrolling, it goes onto a garbage heap so that when a new view scrolls into place it can be reused, rather than requiring a fresh one to be inflated from scratch. That recycled view is the convertView parameter in the getView() method. When your ListView is first populating, convertView will always be null, since the garbage pile has nothing in it, so you're forced to inflate new views, but subsequent calls will likely have that parameter as non-null.
The practical result of this is that when a clicked view that's been set to "Liked" gets recycled, the TextView is still there and still populated with "Liked" rather than the presumed default of "Like". So if you click a view, then scroll down so it goes off the screen, it'll come back around and cause the bug you're seeing.
What you'll probably want to do to fix this is to set the text of likeText within getView() every time, based on what it is in your database. If the post has been liked, set it to "Liked", and if it hasn't, set it to "Like". It should just be one more line, assuming you have easy access to whether or not the post is liked from your DiscussionList object.
P.S. As a side note, hard-coded strings are typically frowned upon in Android, so you may want to move your "Liked" string into the resource files. It's not really necessary unless you're planning to do translations, but it's still good practice.
I am googling for the last few hours, I've seen this question asked like 20 times but none of the solutions seem to work for me. I have a ListView and a CustomList class, that incorporates a list adapter and a simple dialog for editing/removing/renaming items. everything works as supposed until the first screen rotation. After that, the list stops being updated, although the adapter contains all the right data.
I will post both files without skipping a line. I don't need any data being saved at this time, I will handle that later. This is really weird because supposedly the application gets completely restarted after screen rotation. What makes it even stranger, the dummy items are added onCreate even after screen rotation, but after that there is no other response from the list.
Please excuse my english and my noobness and try to point me in the right direction.
package com.sl.mylandmarks;
import android.app.Activity; import android.content.ContentResolver; import android.content.Context; import android.location.LocationManager; import android.os.Bundle; import android.provider.Settings; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView;
public class MainActivity extends Activity {
Button addButton; ListView landmarksList; EditText inputName, inputSearch; CustomList customList; Context globalContext; TextView gpsState; private LocationManager locationManager; private GPSTracker gpsTracker; private double longitude; private double latitude;
#Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
gpsTracker = new GPSTracker(MainActivity.this);
globalContext = this;
addButton = (Button) findViewById(R.id.addBtn);
customList = new CustomList(this);
landmarksList = (ListView) findViewById(R.id.listView1); landmarksList.setAdapter(customList.getAdapter()); landmarksList.setChoiceMode(ListView.CHOICE_MODE_SINGLE); landmarksList.setTextFilterEnabled(true); landmarksList.setLongClickable(true); customList.theList = landmarksList;
inputName = (EditText) findViewById(R.id.EditItemName);
gpsState = (TextView) findViewById(R.id.gpsState);
ContentResolver contentResolver = getBaseContext().getContentResolver(); boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(
contentResolver, LocationManager.GPS_PROVIDER); if (gpsStatus) { gpsState.setText("GPS Enabled"); } else { gpsState.setText("GPS Disabled"); }
// // SEARCH BOX
inputSearch = (EditText) findViewById(R.id.editText3); inputSearch.addTextChangedListener(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) {
customList.getAdapter().getFilter().filter(s); } }); // // SEARCH BOX
// / DUMMY ITEMS customList.addItem("Home", "43.1565 / 15.8645"); customList.addItem("Work", "43.1565 / 15.8645"); customList.addItem("Denis` apartment", "43.1565 / 15.8645"); customList.addItem("Natasa", "43.1565 / 15.8645"); customList.addItem("Bruce Wayne", "43.1565 / 15.8645"); customList.addItem("Walker shop", "43.1565 / 15.8645"); customList.addItem("Chuck Norris Residence", "43.1565 / 15.8645"); customList.addItem("Some landmark", "43.1565 / 15.8645"); // customList.removeItem(3);
OnItemLongClickListener listLongClick = new OnItemLongClickListener() {
#Override public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
customList.showOptionsDialog(arg2);
return true;// event consumed, not dispatched forward } };
landmarksList.setOnItemLongClickListener(listLongClick);
OnClickListener ButtonClick = new View.OnClickListener() {
#Override public void onClick(View v) {
switch (v.getId()) {
case R.id.addBtn:
customList.addItem(inputName.getText().toString(),
"45.5644 / 23.6541");
inputName.setText("");
break;
}
}
};
addButton.setOnClickListener(ButtonClick);
}
#Override public void onPause() { super.onPause();
}
#Override public void onResume() { super.onResume();
}
#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;
}
}
and CustomList.java
package com.sl.mylandmarks;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Dialog;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class CustomList {
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(
2);
HashMap<String, String> maplist;
SimpleAdapter listAdapter;
public Context context;
public ListView theList;
public CustomList(Context con) {
context = con;
String[] from = { "line1", "line2" };
int[] to = { android.R.id.text1, android.R.id.text2 };
listAdapter = new SimpleAdapter(context, list,
android.R.layout.simple_list_item_2, from, to);
}
public void addItem(String name, String coords) {
if ((name != null) && (name.length() != 0)) {
maplist = new HashMap<String, String>();
maplist.put("line1", name);
maplist.put("line2", coords);
list.add(maplist);
listAdapter.notifyDataSetChanged();
}
}
public void removeItem(int id) {
Log.d("removing",list.remove(id).toString());
listAdapter.notifyDataSetChanged();
}
public void renameItem(int id, String newName) {
Log.d("SL","Rename Selected");
maplist = new HashMap<String, String>();
maplist.put("line1", newName);
maplist.put("line2", list.get(id).get("line2"));
list.set(id, maplist);
listAdapter.notifyDataSetChanged();
}
public SimpleAdapter getAdapter() {
return listAdapter;
}
public void showOptionsDialog(final int position) {
//Log.d("SL", String.valueOf(position));
final Dialog optionsDialog = new Dialog(context);
optionsDialog.setContentView(R.layout.list_dialog);
optionsDialog.setTitle("Options");
optionsDialog.show();
final EditText itemNameEdit = (EditText) optionsDialog
.findViewById(R.id.EditItemName);
final Button removeBtn = (Button) optionsDialog
.findViewById(R.id.removeBtn);
final Button renameBtn = (Button) optionsDialog
.findViewById(R.id.renameBtn);
final Button cancelBtn = (Button) optionsDialog
.findViewById(R.id.cancelBtn);
itemNameEdit.setText(list.get(position).get("line1"));
itemNameEdit.setSelection(itemNameEdit.length());
OnClickListener ButtonClick = new View.OnClickListener() {
#Override
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.removeBtn:
removeItem(position);
optionsDialog.dismiss();
break;
case R.id.renameBtn:
renameItem(position, itemNameEdit.getText().toString());
optionsDialog.dismiss();
break;
case R.id.cancelBtn:
optionsDialog.dismiss();
break;
}
}
};
removeBtn.setOnClickListener(ButtonClick);
renameBtn.setOnClickListener(ButtonClick);
cancelBtn.setOnClickListener(ButtonClick);
}
}
I not sure what exactly is your question. And I didn't look at your code, because I don't think that SO is a good place to just dump classes and say "fix this". But I might have an answer for you.
It is true that Android is recreating the activity when you rotate (like roky says). If you come from an iPhone development background (which is my case), it look like kind of weird.
But if your activity is not too complex, you can say to Android to handle it. Do to this, add this to your tag of your AndroidManifest.xml
<activity android:configChanges="orientation|screenSize" ... >
</activity>
Here is a better explanation than mine : android:configChanges="orientation" does not work with fragments
If my answer was the good one, it would be nice to accept it!
I just started with Android programming and here's the thing.
How can i check if the item in GridView was already clicked? Something like assigning a boolean 'clicked' for EACH item in Grid and changing it's value every time i click the item.
Currently i'm just using an array of bools so if i click item[x] it switches the bool[x] and then i do the check if it's true/false and modify the item accordingly, but there has to be a neater way of doing the same!
My code:
package com.example.mojrecnik;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
public class Glavna extends Activity implements AdapterView.OnItemClickListener {
private static final int LENGTH_SHORT = 0;
GridView grid;
TextView tekst;
String[] izfajla = new String[200];
String[] izfajla2 = new String[200];
boolean[] kliknutmrs = new boolean[200];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_glavna);
grid=(GridView)findViewById(R.id.grid);
grid.setAdapter(new MojAdapter());
grid.setOnItemClickListener(this);
//tekst=(TextView)findViewById(R.id.tekst);
citaFajl();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_glavna, menu);
return true;
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
TextView klik = (TextView)arg1.findViewById(R.id.gridtekst2);
if(kliknutmrs[arg2]) {
kliknutmrs[arg2]=!kliknutmrs[arg2];
klik.setText(izfajla[arg2]); }
else {
kliknutmrs[arg2]=!kliknutmrs[arg2];
klik.setText(izfajla2[arg2]); }
}
public void onNothingSelected(AdapterView<?> arg0) {
}
public void citaFajl() {
File kartica = Environment.getExternalStorageDirectory();
File fajl = new File(kartica, "reci.txt");
StringBuilder tekst = new StringBuilder();
int i=0;
try {
BufferedReader br = new BufferedReader(new FileReader(fajl));
String linija;
String[] prva;
while ((linija = br.readLine())!=null) {
prva = linija.split("-");
izfajla[i]=prva[0];
if(prva[1].length()>0)
izfajla2[i]=prva[1];
i++;
}
}
catch (IOException e) {
Toast greska = Toast.makeText(this, e.getMessage().toString(), LENGTH_SHORT);
greska.show();
}
}
private class MojAdapter extends ArrayAdapter {
public MojAdapter() {
super(Glavna.this, R.layout.gridvju, izfajla);
}
public View getView(int position, View convertView, ViewGroup parent) {
//vazno!! pravim vju od inflatera i vracam vju a ne convertvju!
View gridvju;
if(convertView==null) {
LayoutInflater inflater = getLayoutInflater();
gridvju = inflater.inflate(R.layout.gridvju, parent, false);
}
else
gridvju=convertView;
TextView tekst2 = (TextView)gridvju.findViewById(R.id.gridtekst2);
tekst2.setLines(2);
tekst2.setText(izfajla[position]);
return(gridvju);
}
}
}
And XML(main):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!--
<TextView
android:id="#+id/tekst"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textSize="20dp"
android:layout_below="#id/tekst" >
</TextView> -->
<GridView
android:id="#+id/grid"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:horizontalSpacing="#dimen/padding_medium"
android:numColumns="3"
android:stretchMode="columnWidth" >
</GridView>
</RelativeLayout>
And layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/gridtekst2" />
</LinearLayout>
Here is how i worked it in the end. I created a custom class to contain text which is displayed and also added a bool in there so now every element in my gridview has its own 'click-checker'.
note: this program simply alternates between 2 words onClick, if you wanna try it use text file with data formated 'word1 - word2'
Code:
package com.example.mojrecnik;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;
public class Glavna extends Activity implements AdapterView.OnItemClickListener {
private static final int LENGTH_LONG = 1;
GridView grid;
List<Rec> lReci = new ArrayList<Rec>(); //this is our list of data which contains text and bool check
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_glavna);
citaFajl();
grid=(GridView)findViewById(R.id.grid);
grid.setAdapter(new MojAdapter());
grid.setOnItemClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_glavna, menu);
return true;
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
VjuHolder holder=(VjuHolder)arg1.getTag();
if(!lReci.get(arg2).clicked)
holder.text.setText(lReci.get(arg2).rec2);
else
holder.text.setText(lReci.get(arg2).rec1);
lReci.get(arg2).clicked = !lReci.get(arg2).clicked;
}
public void onNothingSelected(AdapterView<?> arg0) {
//////////////////////////////////////////
}
public void citaFajl() {
try {
BufferedReader br = new BufferedReader(new FileReader(new File(Environment.getExternalStorageDirectory(), "reci.txt")));
String[] reci = new String[2];
String linija;
Rec rec;
while ((linija = br.readLine()) != null) {
reci = linija.split("-"); //because data in my file is formatted 'word1 - word2', we separate them now so we can alternate between them
reci[1]=reci[1].trim();
rec = new Rec(reci[0], reci[1], false);
lReci.add(rec);
}
}
catch (IOException e) {
Toast.makeText(this, e.getMessage().toString(), LENGTH_LONG).show();
}
}
private class MojAdapter extends ArrayAdapter<String> {
public MojAdapter() {
super(Glavna.this, R.layout.gridvju);
}
public int getCount() {
return lReci.size(); //here we explicitly set the total number of grid elements so it doesn't go out of index range
}
public View getView(int position, View convertView, ViewGroup parent) {
VjuHolder holder;
if(convertView==null) {
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.gridvju, parent, false);
holder = new VjuHolder();
holder.text = (TextView)convertView.findViewById(R.id.gridtekst2);
convertView.setTag(holder); }
else
holder=(VjuHolder)convertView.getTag();
if(lReci.get(position).clicked) //check to make grid update according to the clicked state of our elements [when scrolling]
holder.text.setText(lReci.get(position).rec2);
else
holder.text.setText(lReci.get(position).rec1);
holder.text.setLines(2);
return(convertView);
}
}
}
//holder class
class VjuHolder {
TextView text;
}
//here we put the text to be displayed along with bool to check in which state is the clicked element
class Rec {
String rec1, rec2;
boolean clicked;
Rec(String rec, String druga, boolean klik) {
rec1 = rec;
rec2 = druga;
clicked = klik;
}
}
There's no such thing like "click history" retained. If user taps anything then, if there's onClickListener assigned, you will get notified about that tap. But you cannot check that by querying UI objects. Boolean array is ok, but I'd use List or ArrayList instead and simply add id of tapped items in my onClickListener.
There is no way to find out whether button was clicked before or not. I think you've been looking for some sort of class property like
if(button.wasOnceClicked){ //THERE IS NO CODE LIKE THIS
}
Am I right? Well, Button class dont have this.
However u can create subclass of Button and add that property and also add some code which will handle that property.
First of all initialize your boolean array in onCreate as:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid);
grid=(GridView)findViewById(R.id.grid);
grid.setAdapter(new MojAdapter());
grid.setOnItemClickListener(this);
// HERE I have initialized with true valuse
for(int i=0; i<kliknutmrs.length; i++) {
kliknutmrs[i] = true;
}
//tekst=(TextView)findViewById(R.id.tekst);
citaFajl();
}
Then at onClick, just ckeck that the boolean array hav "true" value; so make that position value "false" and same time invert the text value with another String[] array.
At second time it will goto to else part:
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
TextView klik = (TextView)arg1.findViewById(R.id.gridtekst2);
if(kliknutmrs[arg2]) {
System.out.println(" ------------ 11111111111 -----------");
kliknutmrs[arg2]=!kliknutmrs[arg2];
klik.setText(izfajla2[arg2]); }
else {
System.out.println(" ------------- 222222222 -----------");
// NO NEED //kliknutmrs[arg2]=!kliknutmrs[arg2];
klik.setText(izfajla2[arg2]); }
}