I want to show some contacts information those are stored in a file in the list view.I want each contact to be shown in a separate cell rather than all together in a same place.Now all the contacts are showing in a single cell in the list view.I used a special character to check the end of a contact information.
Thanks in advance :)
Here is my code:
public void show_contacts()
{
final ListView listview = (ListView) findViewById(R.id.listview);
final ArrayList<String> list = new ArrayList<String>();
final ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, list);
String data_read="";
String FILENAME = "myfile.txt";
StringBuffer fileContent = new StringBuffer("");
FileInputStream fis = null;
String s1="";
try {
fis = openFileInput("myfile.txt");
byte[] buffer = new byte[1];
while (fis.read(buffer) != -1) {
if(s1.endsWith("."))
{
data_read=fileContent.toString();
list.add(data_read);
}
else
s1+=buffer.toString();
fileContent.append(new String(buffer));
}
} catch (Exception e) {
e.printStackTrace();
}
data_read=fileContent.toString();
list.add(data_read);
listview.setAdapter(adapter);
}
public void Write_to_file(String cName2,String cNumber2)
{
String string=cName2+"--"+cNumber2;
String FILENAME="myfile.txt";
FileOutputStream fos = null;
Context c=this.getBaseContext();
try {
String s=".";
fos = c.openFileOutput(FILENAME, Context.MODE_APPEND);
fos.write(string.getBytes());
fos.write(s.getBytes());
fos.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
My wish is you don't write the contact name into text file you Just write your Contacts in the custom Class like
public class Sample {
private String listitem1;
private String listitem2;
public String getListitem1() {
return listitem1;
}
public void setListitem1(String listitem1) {
this.listitem1 = listitem1;
}
public String getListitem2() {
return listitem2;
}
public void setListitem2(String listitem2) {
this.listitem2 = listitem2;
}
}
And use this custom adapter in your program...
public class CustomAdapter extends ArrayAdapter<Sample> {
public ArrayList<Sample> mlist;
public Context context;
public LayoutInflater inflater;
public CustomAdapter(Context context, int resource, ArrayList<Sample> mlist) {
super(context, resource);
this.mlist = mlist;
this.context = context;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getPosition(Sample item) {
return super.getPosition(item);
}
#Override
public Sample getItem(int position) {
return mlist.get(position);
}
#Override
public int getCount() {
return mlist.size();
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = inflater.inflate(R.layout.listitem, null);
TextView text1 = (TextView) convertView.findViewById(R.id.item1);
TextView text2 = (TextView) convertView.findViewById(R.id.item2);
text1.setText(mlist.get(position).getListitem1());
text2.setText(mlist.get(position).getListitem2());
return convertView;
}
}
And use this code into your Activity....
private ArrayList<Sample> mListItems;
private PullToRefreshListView mPullRefreshListView;
private CustomAdapter mAdapter;
private String[] mStrings = { "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
"Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale", "Aisy Cendre",
"Allgauer Emmentaler", "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
"Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale", "Aisy Cendre",
"Allgauer Emmentaler" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ptr_list);
mListItems= new ArrayList<Sample>();
mPullRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);
Calculation();
mPullRefreshListView.setAdapter(mAdapter);
}
private void Calculation() {
for(int i=0;i<mStrings.length;i++)
{
Sample sample = new Sample();
sample.setListitem1(mStrings[i]);
sample.setListitem2(mStrings[i]);
mListItems.add(sample);
}
}
And you just replace with you Contact Name and Number in the Above sample..
Related
I'm developing an Android app using Google Sheets as a database.
I have information about books in a Google Sheet (title, author, cover, date, etc). I want to retrieve this information and show it in a "Listview" in the "Spreadsheets" Activity. I created a "BookItem" object and an "BookAdapter" adapter. In the "Spreadsheets.java" I have the read method, called "getDataFromApi()". I know that this method works, but I don't know how to adapt it to my "BookAdapter" and show the information on the ListView.
This is mi code:
public class BookItem {
static String title_item;
static Drawable cover_item; //probar con String
public BookItem(String title, Drawable cover){
super();
this.title_item = title;
this.cover_item = cover;
}
public String getTitle() {
return title_item;
}
public void setTitle(String title){
this.title_item = title;
}
public static Drawable getCover() {
return cover_item;
}
public void setCover(Drawable cover) {
this.cover_item = cover;}
This is my BookAdapter:
public class BookAdapter extends BaseAdapter {
private ArrayList<BookItem> items;
List<BookItem> items;
private Context context;
public BookAdapter (Context context, List<BookItem> items) {
this.context = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public BookItem getItem(int position) {
return this.items.get(position);
}
#Override
public long getItemId(int i) {
return 0;
}
private static class ViewHolder {
public final ImageView cover_item;
public final TextView title_item;
public ViewHolder (ImageView cover_item, TextView title_item){
this.cover_item = cover_item;
this.title_item = title_item;
}
}
#Override
public View getView (int position, View view, ViewGroup viewGroup) {
ImageView cover_item;
TextView title_item;
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.fila_lista_miestanteria, viewGroup, false); //se mete aqui en getView por ser baseAdapter
title_item = (TextView) view.findViewById(R.id.book_title_item);
cover_item = (ImageView) view.findViewById(R.id.book_cover_item);
view.setTag(R.id.book_title_item, title_item);
view.setTag(R.id.book_cover_item, cover_item);
}
else {
cover_item = (ImageView) view.getTag(R.id.book_cover_item);
title_item = (TextView)view.getTag(R.id.book_title_item);
}
BookItem bookItem = getItem(position);
cover_item.setImageDrawable(bookItem.getCover());
title_item.setText(bookItem.getTitle());
return view;
}
}
public class Spreadsheets extends Activity {
static String book_title, book_author, book_date, book_category, book_description, book_rating, book_cover;
static String read_only = "no";
static String book_favorite = "no";
static GoogleAccountCredential mCredential;
private ListView bookList;
private TextView mOutputText;
ProgressDialog mProgress;
Context context;
List<String> rst;
List<BookItem> resultados;
BookAdapter adapter;
private static final String[] SCOPES = {SheetsScopes.SPREADSHEETS};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spread);
// mOutputText = (TextView) findViewById(R.id.outputText);
bookList = (ListView) findViewById(R.id.bookList);
// mOutputText.setText("");
mProgress = new ProgressDialog(this);
mProgress.setMessage("Calling Google Sheets...");
// Initialize credentials and service object.
mCredential = GoogleAccountCredential.usingOAuth2(
getApplicationContext(), Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff());
System.out.print("read only es igual a "+ read_only);
new MakeRequestTask(mCredential).execute();
}
public void rellenar(){
System.out.println("VOY A HACER NEW BOOK ADAPTER ");
adapter = new BookAdapter(context, resultados);
bookList.setAdapter(adapter);
System.out.println("SETADAPTER");
}
private class MakeRequestTask extends AsyncTask<Void, Void, List<String>> {
private Exception mLastError = null;
MakeRequestTask(GoogleAccountCredential credential) {
}
#Override
protected List<String> doInBackground(Void... params) {
try {
if(read_only.equals("no")) {
setDataToApi();
return null;
}
else {
return getDataFromApi();
}
} catch (Exception e) {
mLastError = e;
cancel(true);
return null;
}
}
private List<String> getDataFromApi() throws IOException {
String range = "Sheet1!A1:H";
List<String> results = new ArrayList<String>();
ValueRange response = CreateSpreadsheets.mService.spreadsheets().values()
.get(CreateSpreadsheets.spreadsheet_id, range)
.execute();
List<List<Object>> values = response.getValues();
if (values != null) {
for (List row : values) {
results.add(row.get(0) + ", " + row.get(7));
}
}
//funcion();
return results;
}
private void setDataToApi() throws IOException {
String range = "Sheet1!A2:H";
List<List<Object>> values = new ArrayList<>();
List<Object> data1 = new ArrayList<>();
data1.add(book_title);
data1.add(book_author);
data1.add(book_date);
data1.add(book_category);
data1.add(book_description);
data1.add(book_rating);
data1.add(book_cover);
data1.add("a");
values.add(data1);
ValueRange valueRange = new ValueRange();
valueRange.setMajorDimension("ROWS");
valueRange.setRange(range);
valueRange.setValues(values);
ValueRange body = new ValueRange().setValues(values);
AppendValuesResponse response =
CreateSpreadsheets.mService.spreadsheets().values().append(CreateSpreadsheets.spreadsheet_id, range, body)
.setValueInputOption("RAW")
.execute();
}
#Override
protected void onPreExecute() {
//mOutputText.setText("");
mProgress.show();
}
#Override
protected void onPostExecute(List<String> output) {
mProgress.hide();
if (output == null || output.size() == 0) {
// mOutputText.setText("No results returned.");
} else {
if(read_only.equals("no")) {
Intent intent = new Intent(Spreadsheets.this, MainActivity.class);
startActivity(intent);
// mOutputText.setText("Se ha añadido un libro a su lista");
}
else {
System.out.println("VOY A RELLENAR LA LISTA");
rellenar();
}
}
}
#Override
protected void onCancelled() {
}
}
}
The "spread.xml" is a list, and the "fila_list_miestanteria.xml" is a TextView&ImageView to show the book info.
Thank you so much!
How do i able to convert from an integer number that is get from mysql database into time format? Here are my java files
parking_records.java with arrayAdapter
public class parking_records extends ArrayAdapter<String> {
private String[] Parking_Start_Time;
private String[] Parking_End_Time;
private String[] Duration;
private Activity context;
public parking_records(Activity context, String[] Parking_Start_Time, String[] Parking_End_Time, String[] Duration) {
super(context, R.layout.fragment_parking_record, Parking_Start_Time);
this.context = context;
this.Parking_Start_Time = Parking_Start_Time;
this.Parking_End_Time = Parking_End_Time;
this.Duration = Duration;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View listViewItem = inflater.inflate(R.layout.fragment_parking_record, null, true);
TextView textViewPRd = (TextView) listViewItem.findViewById(R.id.textViewPRd);
TextView textViewPRd1 = (TextView) listViewItem.findViewById(R.id.textViewPRd1);
TextView textViewPRr = (TextView) listViewItem.findViewById(R.id.textViewPRr);
textViewPRd.setText(Parking_Start_Time[position]);
textViewPRd1.setText(Parking_End_Time[position]);
textViewPRr.setText(Duration[position]);
return listViewItem;
}
}
Parking_Records.java
public class Parking_Records {
public static String[] Parking_Start_Time;
public static String[] Parking_End_Time;
public static String[] Duration;
public static final String JSON_ARRAY = "result";
public static final String KEY_ParkStartTime = "Parking_Start_Time";
public static final String KEY_ParkEndTime = "Parking_End_Time";
public static final String KEY_ParkDuration = "Duration";
private JSONArray users = null;
private String json;
public Parking_Records(String json){
this.json = json;
}
public void parseJSON(){
JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY);
Parking_Start_Time = new String[users.length()];
Parking_End_Time = new String[users.length()];
Duration = new String[users.length()];
for(int i=0;i<users.length();i++){
JSONObject jo = users.getJSONObject(i);
Parking_Start_Time[i] = jo.getString(KEY_ParkStartTime);
Parking_End_Time[i] = jo.getString(KEY_ParkEndTime);
Duration[i] = jo.getString(KEY_ParkDuration);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Main Parking_Records_Fragment.java
public class ParkingRecordFragment extends Fragment implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
ProgressDialog dialog;
String url;
SessionManager session;
private String Username;
private String Acc_Pass;
SharedPreferences shared;
private SwipeRefreshLayout mSwipeRefreshLayout;
public ParkingRecordFragment() {
// Required empty public constructor
}
private ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("Parking Record");
// Session class instance
session = new SessionManager(getActivity().getApplicationContext());
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Loading....");
dialog.show();
View rootView = inflater.inflate(R.layout.activity_listview_parking_records, container, false);
listView = (ListView) rootView.findViewById(R.id.listView);
listView.setEmptyView(rootView.findViewById(R.id.empty_list_item));
mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh_layout);
mSwipeRefreshLayout.setOnRefreshListener(this);
mSwipeRefreshLayout.postDelayed(new Runnable() {
#Override
public void run() {
mSwipeRefreshLayout.setRefreshing(false);
sendRequest(Username, Acc_Pass);
}
}, 1000);
sendRequest(Username, Acc_Pass);
shared= getActivity().getSharedPreferences("Mypref", Context.MODE_PRIVATE);
return rootView;
}
#Override
public void onRefresh() {
sendRequest(Username, Acc_Pass);
}
private void sendRequest(String Username, String Acc_Pass){
HashMap<String, String> user = session.getUserDetails();
Username = user.get(SessionManager.KEY_USERNAME);
Acc_Pass = user.get(SessionManager.KEY_PASSWORD);
RequestQueue requestQueue = VolleyController.getInstance(getActivity().getApplicationContext()).getRequestQueue();
String url = "http://192.168.1.5/json_parking_records2.php?Username="+Username+"&Acc_Pass="+Acc_Pass+"";
url = url.replaceAll(" ", "%20");
try {
URL sourceUrl = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
Log.i("Getting url info",""+url);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
showJSON(response);
dialog.dismiss();
mSwipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity().getApplicationContext(),error.getMessage(),Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
requestQueue.add(stringRequest);
}
private void showJSON(String json){
Parking_Records pj = new Parking_Records(json);
pj.parseJSON();
parking_records cl = new parking_records(getActivity(), Parking_Records.Parking_Start_Time, Parking_Records.Parking_End_Time, Parking_Records.Duration);
listView.setAdapter(cl);
}
#Override
public void onClick(View v) {
sendRequest(Username, Acc_Pass);
}
}
Android screenshot
So right now i've been struggling of how do i able to convert from an integer number to a time format. Please guide me. Thanks
I have solved my question on my own successfully. Here is the code.
textViewPRr.setText(String.format("%d:%02d:%02d", (Duration[position]/3600), (Duration[position]%3600)/60, (Duration[position]%60)));
I set that in parking_records.java with arrayAdapter
Hope that this answer can help others!
I have problem to set data into listview. Problem occurs after set message, message is set first after come 8th message from thread.
**below is my whole code :****(Here is my "Activity and adapter")**
public class Inboxreadmsg extends ActionBarActivity {
// <strong>Here is my global variable</strong>
ListView lv;
Handler h;
Custom_Inbox_Adapter ccAdpt;
Custom_Inbox_Adapter inadapter;
Runnable checker;
List<Dataset> dataset;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.messagesublistlayout);
// map id from layout</strong>
lv =(ListView)findViewById(R.id.readmessagelist);
/*****************************call thread of webservice with database****************************/
runThread();
startHandler();
/*****************************call thread of webservice with database****************************/
}
public void runThread()
{
h=new Handler();
checker=new Runnable()
{
#Override
public void run() {
// call webservice for fetch data
forthread();
h.postDelayed(checker,15000);
}
};
}
public void forthread()
{
// call webservice to fetch data
new InboxReadChat(null, InboxReadChat.TotalMessagesOfSingleSenderUser.geturl( recipientid,InAppUserid), InboxReadChat.TYPE_GET, InboxReadChat.TYPE_RECEIVE_MESSAGE_INBOX, new ServiceHitListenerInboxChat() {
#Override
public void onSuccess(Object Result, int id)
{
// After success of webservice response come this function
callFxnInSuccess(Result);
}
#Override
public void onError(String Error, int id)
{
// AfterError of webservice response come this function
// By this fxn set data from local database to listview
DBvaluesSet();
}
});
}
private void callFxnInSuccess(Object Result) {
dataset = new ArrayList<Dataset>();
String message="",alldatetime="",time="",date="",type="";
InboxDeliveredModel ibx=(InboxDeliveredModel) Result;
if(ibx.getTotalMessagesOfSingleSenderUser().size()>0)
{
// here webservice response data will add on local database
dbObject.Open();
for(int i=0;i<ibx.getTotalMessagesOfSingleSenderUser().size();i++)
{
message =ibx.getTotalMessagesOfSingleSenderUser().get(i).getMessage();
.....
dbObject.InboxMessageAll(message,InAppUsermobile,time,recipientid,type,date);
}
dbObject.close();
// After add data into database call below fxn to fetch data from database and set data in listview with adapter
try
{
DBvaluesSet();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public void DBvaluesSet() {
dataset = new ArrayList<Dataset>();
try
{
// By this code fetch data from local database
Cursor c;
dbObject.Open();
c=dbObject.getallmessages(recipientid);
int countRow = c.getCount();
int counter = 0;
while(c.moveToNext())
{
msgboxitem = c.getString(0);
// number = c.getString(1);
timeitem = c.getString(2);
typeitem = c.getString(4);
datedbitem = c.getString(5);
try {
dataset.add(db.new Dataset(datedbitem, msgboxitem, timeitem, typeitem));
} catch (Exception e) {
e.printStackTrace();
}
}
dbObject.close();
// by below set data into listview into adapter
lv.setAdapter(ccAdpt=new Custom_Inbox_Adapter( getApplicationContext(),dataset,R.layout.row));
ccAdpt.notifyDataSetChanged();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Here my adapter coding...
public class Custom_Inbox_Adapter extends BaseAdapter{
private Context gContext;
private List<Dataset> gData;
private int rEsource;
public Custom_Inbox_Adapter(Context cnt, List<Dataset> data ,int resource){
this.gData = data;
this.gContext = cnt;
this.rEsource = resource;
}
#Override
public int getCount() {
return gData.size();
}
#Override
public Dataset getItem(int position) {
return gData.get(position);
}
#Override
public long getItemId(int position) {> return gData.get(position).hashCode();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) gContext.getSystemService(gContext.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(rEsource, null);
TextView txtReceiveMsg = (TextView) convertView.findViewById(R.id.ReceiveMsg);
TextView txtReceiveTime = (TextView) convertView.findViewById(R.id.ReceiveTime);
TextView txtSendMsg = (TextView) convertView.findViewById(R.id.sendMsg);
TextView txtSendTime = (TextView) convertView.findViewById(R.id.senttime);
TextView date = (TextView) convertView.findViewById(R.id.date);
// layout text chat
RelativeLayout relSend = (RelativeLayout) convertView.findViewById(R.id.LinearReceive);
RelativeLayout relreceive = (RelativeLayout) convertView.findViewById(R.id.LinearSend);
// layout date chat
RelativeLayout LinearDATE= (RelativeLayout) convertView.findViewById(R.id.LinearDATE);
if(position == 0){
fetchdata= gData.get(position).getDate().trim();
date.setText(fetchdata);
}
else{
fetchdata = gData.get(position).getDate().trim();
dd = gData.get((position-1)).getDate().trim();
if(fetchdata.equalsIgnoreCase(dd))
{
LinearDATE.setVisibility(View.GONE);
}
else
{
LinearDATE.setVisibility(View.VISIBLE);
Log.w("INBOX READ", "INBOX_READ_ADAPTER::::(date for position '1'):"+fetchdata);
date.setText(fetchdata);
}
}
relreceive.setVisibility(View.GONE);
relSend.setVisibility(View.VISIBLE);
//txtReceiveNumber.setText(number);
txtReceiveMsg.setText(cutmsg);
txtReceiveTime.setText(time);
}
return convertView;
}
}
I'm using this library: https://github.com/shontauro/android-pulltorefresh-and-loadmore to add items at my lisview when scrolling reach the end. Actually it works. It load new data but it doesn't "append" it to the listview. It simply reload a new list. I need add my new data at the old as the library do! This is what i done so far:
i declared these:
String[] provaArr;
private LinkedList<String> mList;
then:
mList = new LinkedList<String>();
provaArr = (titoli.toArray(new String[0]));
mList.addAll(Arrays.asList(provaArr));
lista = (LoadMoreListView)view.findViewById(R.id.main_lista);
lista.setOnLoadMoreListener(new OnLoadMoreListener() {
public void onLoadMore() {
new ParsingSecondPage().execute();
}
});
And the AsynkTask:
private class ParsingSecondPage extends AsyncTask<String,String,String> {
#Override
protected void onPreExecute()
{
//prima di eseguire il parsing inizializzo gli arraylist
super.onPreExecute();
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setTitle("Loading");
mProgressDialog.setMessage("please wait...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
mProgressDialog.setCanceledOnTouchOutside(false);
titoli = new ArrayList<String>();
data = new ArrayList<String>();
categoria = new ArrayList<String>();
Lurl = new ArrayList<String>();
}
#Override
protected String doInBackground(String... params) {
if (isCancelled()){
return null;
}
try {
current += 1;
BLOG_URL_SECOND = "http://www.page.it/articoli/?pagina="+current;
Document doc = Jsoup.connect(BLOG_URL_SECOND)
.get();
Elements sezioni = doc.getElementsByClass("archive_box");
for (Element riga : sezioni) {
Element info = riga.getElementsByClass("text").first();
// Title
titolo = riga.select("h2").text();
titoli.add(titolo);
// Url
String urltitle = riga.select("h2 a").first().attr("abs:href");
Lurl.add(urltitle);
// Date
String date = info.getElementsByClass("date").first().text();
System.out.println(date);
data.add(date);
// categoria
String category = info.getElementsByClass("category").first().text();
System.out.println(category);
categoria.add(category);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < provaArr.length; i++)
mList.add(provaArr[i]);
return null;
}
#Override
protected void onPostExecute(String result)
{
adapter.notifyDataSetChanged();
lista.onLoadMoreComplete();
new LogoSecond().execute();
mProgressDialog.dismiss();
}
}
So, when i reach the end of page it call the AsynkTask but instead add the items it reload the page with new datas.
ADAPTER:
public class ParsingArrayAdapter extends ArrayAdapter<String>{
private final static int LAYOUT = R.layout.riga_listview;
private final static int TITOLO = R.id.riga_listview_titolo;
private final static int DATA = R.id.riga_listview_data;
private final static int CATEGORIA = R.id.riga_listview_categoria;
private final static int IMMAGINE = R.id.imageView1;
ArrayList<Bitmap> bitmap;
ArrayList<String> links;
ArrayList<String> titoli;
ArrayList<String> data;
ArrayList<String> categoria;
Context c;
LayoutInflater inflater;
public ParsingArrayAdapter(Context context,ArrayList<String> titoli, ArrayList<Bitmap> bitmap, ArrayList<String> data, ArrayList<String> categoria)
{
super(context,TITOLO);
this.c = context;
this.titoli = titoli;
this.data = data;
this.categoria = categoria;
this.bitmap = bitmap;
this.inflater = LayoutInflater.from(c);
}
#Override
public int getCount()
{
return titoli.size();
}
//quando la lista richiede una view
#SuppressLint("NewApi")
#Override
public View getView(int pos,View view,ViewGroup parent)
{
CacheRiga cache;
if(view==null)
{
view = inflater.inflate(LAYOUT, parent,false);
cache = new CacheRiga(); //inizializzo la cache
cache.titolo = (TextView) view.findViewById(TITOLO); //collego titolo
cache.dateArticoli = (TextView) view.findViewById(DATA); //collego la data
cache.categoriatext = (TextView) view.findViewById(CATEGORIA); //collego la data
cache.immagini = (ImageView) view.findViewById(IMMAGINE);//collego descrizione
view.setTag(cache);//collego view con cache
}
else
{
cache = (CacheRiga) view.getTag();
}
if (this.titoli.size() > 0 && pos < this.titoli.size()){
cache.titolo.setText(titoli.get(pos)); //imposto il titolo
}
if (this.data.size() > 0 && pos < this.data.size()){
cache.dateArticoli.setText(data.get(pos));
}
cache.categoriatext.setText(categoria.get(pos));
cache.immagini.setImageBitmap(bitmap.get(pos));
if (bitmap!=null){
Log.d("Bitmap MP.it", "BitmapNOTnull");
}else{
Log.d("Bitmap null MP.it", "Bitmapnull");
}
if (data!=null){
Log.d("Data", "Data NOT null");
}else{
Log.d("Data", "Data null");
}
return view;
}
private class CacheRiga { // classe per la cache delle righe
public TextView titolo; // cache titolo
public TextView dateArticoli; // cache data
public TextView categoriatext; // cache categoria
public ImageView immagini; // cache descrizione
}
MainMenulist.java In this class string array store all values public String[] itemcodes; i want access itemcodes to Main.java
Main.java
JSONArray json = jArray.getJSONArray("mainmenu");
list=(ListView)findViewById(R.id.mainmenulist);
adapter=new MainMenulist(this, json);
list.setAdapter(adapter);
MainMenulist.java
public class MainMenulist extends BaseAdapter {
protected static Context Context = null;
int i;
public String editnewmainmenu,menuname;
String qrimage;
Bitmap bmp, resizedbitmap;
Bitmap[] bmps;
Activity activity = null;
private LayoutInflater inflater;
private ImageView[] mImages;
String[] itemimage;
TextView[] tv;
String itemname,itemcode;
public String[] itemnames,itemcodes;
HashMap<String, String> map = new HashMap<String, String>();
public MainMenulist(Context context, JSONArray imageArrayJson) {
Context = context;
// inflater =
// (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// imageLoader=new ImageLoader(activity);
inflater = LayoutInflater.from(context);
this.mImages = new ImageView[imageArrayJson.length()];
this.bmps = new Bitmap[imageArrayJson.length()];
this.itemnames = new String[imageArrayJson.length()];
this.itemcodes=new String[imageArrayJson.length()];
try {
for (i = 0; i < imageArrayJson.length(); i++) {
JSONObject image = imageArrayJson.getJSONObject(i);
qrimage = image.getString("menuimage");
itemname = image.getString("menuname");
itemcode=image.getString("menucode");
itemnames[i] = itemname;
itemcodes[i]=itemcode;
byte[] qrimageBytes = Base64.decode(qrimage.getBytes());
bmp = BitmapFactory.decodeByteArray(qrimageBytes, 0,
qrimageBytes.length);
int width = 100;
int height = 100;
resizedbitmap = Bitmap.createScaledBitmap(bmp, width, height,
true);
bmps[i] = bmp;
mImages[i] = new ImageView(context);
mImages[i].setImageBitmap(resizedbitmap);
mImages[i].setScaleType(ImageView.ScaleType.FIT_START);
// tv[i].setText(itemname);
}
System.out.println(itemnames[i]);
System.out.println(map);
} catch (Exception e) {
// TODO: handle exception
}
}
public int getCount() {
return mImages.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
vi = inflater.inflate(R.layout.mainmenulistview, null);
final TextView text = (TextView) vi.findViewById(R.id.menutext);
ImageView image = (ImageView) vi.findViewById(R.id.menuimage);
System.out.println(itemcodes[position]);
image.setImageBitmap(bmps[position]);
text.setText(itemnames[position]);
text.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
if(itemcodes[position].equals("1"))
{
Intent intent = new Intent(Context, FoodMenu.class);
System.out.println("prakash");
Context.startActivity(intent);
}
else {
Toast.makeText(Context, "This Feauture is not yet Implemented",4000).show();
}
}
});
return vi;
}
}
MainMenulist.java System.out.println(itemcodes[position]); here i print all the codes .no w i want print same result in Main.java
Write a bean which implements serlizable,write setter and getter method for your array(itemnames) as follows
class Bean implements Serializable{
String itemnames[];
public Hashtable getItemnames() {
return itemnames;
}
public void setItemnames(String itemnames[]) {
this.itemnames= itemnames;
}
}
And write foollowing code in calling activity
Bean b = new Bean();
b.setItemnames(itemnames);
Intent i=new Intent();
i.setClass(A.this,B.class);
i.putExtra("itemnames", b);
startActivity(i);
And retrieve in called activity as follows
Bean obj = (Bean) getIntent().getSerializableExtra("itemnames");// TypeCasting
String itemname[] = (Hashtable) obj.getItemnames();
There are two ways to do this:
In your code:
public String[] itemnames,itemcodes; make that arrays as static like below
public static String[] itemnames,itemcodes;
And then use `Main.java` file by calling:
System.out.println(MainMenulist.itemcodes[position]);
System.out.println(MainMenulist.itemnames[position]);
2) Parse JSON in Main.java which you have pass to MainMenulist.java
public MainMenulist(Context context, JSONArray imageArrayJson)