i need to be able to make calls from an activity. so here is a my activity that shows details of people and i have a call button. but i get a nullPointerError when i call the setOnClickListener(...). why? thnks for any help.
package com.AndroidApp.pagine;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.AndroidApp.ApplicationController;
import com.AndroidApp.R;
import com.AndroidApp.XMLFunctions;
import com.AndroidApp.Login.LoginActivity;
import com.AndroidApp.domain.Anagrafica;
public class DettagliPagina extends ListActivity {
public Anagrafica anagrafica;
public ArrayList<HashMap<String, String>> mylist;
private boolean paused, newIntentSelected = false;
private ProgressDialog progressDialog;
private SharedPreferences mPreferences;
public ApplicationController ac;
private Button bCall;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ac = (ApplicationController)getApplication();
mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
String nome = mPreferences.getString("nome", "Errore");
String cognome = mPreferences.getString("cognome", "Errore");
setTitle("Sessione di : " + nome + " " + cognome);
new BackgroundAsyncTask().execute();
}
#Override
protected void onStart() {
super.onStart();
bCall = (Button) findViewById(R.id.bCall);
// add PhoneStateListener
PhoneCallListener phoneListener = new PhoneCallListener();
TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
telephonyManager.listen(phoneListener, PhoneStateListener.LISTEN_CALL_STATE);
// add button listener
bCall.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:3492395504"));
startActivity(callIntent);
}
});
}
#Override
protected void onPause() {
super.onPause();
paused = true;
ac.setOraAttuale(Calendar.getInstance());
ac.oraAttuale.add(Calendar.MINUTE, 1);
ac.setOraScadenza(ac.getOraAttuale());
Log.d("DettagliPAgina scadenza", ac.getOraScadenza().getTime().toString());
}
#Override
protected void onResume() {
super.onResume();
if (ac.isKill) {
finish();
}
if (paused && !newIntentSelected){
if (Calendar.getInstance().after(ac.getOraScadenza())){
//torna al login con toast sessione scaduta
ac.setSessioneTerminata(true);
Toast.makeText(getApplicationContext(), "Sessione Scaduta", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(DettagliPagina.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
}
public class BackgroundAsyncTask extends
AsyncTask<String, Integer, ArrayList<HashMap<String, String>>> {
#Override
protected ArrayList<HashMap<String, String>> doInBackground(
String... paths) {
mylist = new ArrayList<HashMap<String, String>>();
String xml = XMLFunctions.getXML();
Document doc = XMLFunctions.xmlFromString(xml);
int numResults = XMLFunctions.numResults(doc);
if ((numResults <= 0)) {
Log.i("doInBack", "nussun risultato");
DettagliPagina.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Nessun risultato trovato", Toast.LENGTH_LONG).show();
}
});
Intent intent = new Intent(DettagliPagina.this, FiltriAnagraficaPagina.class);
startActivity(intent);
}
Bundle extras = getIntent().getExtras();
int id = 0;
System.out.print(id);
if (extras != null) {
id = extras.getInt("id");
}
Log.i("Dettagli", "D1");
Set<Anagrafica> anagrafici = new HashSet<Anagrafica>();
NodeList nodes = doc.getElementsByTagName("anagrafica");
Element e = (Element) nodes.item(id);
anagrafica = new Anagrafica();
anagrafica.setId(XMLFunctions.getValue(e, "idAnagrafica"));
anagrafica.setNome(XMLFunctions.getValue(e, "nome"));
anagrafica.setCognome(XMLFunctions.getValue(e, "cognome"));
anagrafica.setIndirizzo(XMLFunctions.getValue(e, "indirizzo"));
anagrafica.setDataDiNascita(XMLFunctions.getValue(e, "dataDiNascita"));
anagrafica.setEmail(XMLFunctions.getValue(e, "email"));
anagrafica.setTipologiaUtente(XMLFunctions.getValue(e, "tipologieUtente"));
anagrafica.setAziendaCollegata(XMLFunctions.getValue(e, "aziendaCollegata"));
anagrafica.setTelefono(XMLFunctions.getValue(e, "telefono"));
anagrafica.setCellulare(XMLFunctions.getValue(e, "cellulare"));
anagrafica.setInteressi(XMLFunctions.getValue(e, "interessi"));
anagrafica.setRiferimenti(XMLFunctions.getValue(e, "riferimenti"));
anagrafici.add(anagrafica);
HashMap<String, String> map = new HashMap<String, String>();
map.put("idAnagrafica",anagrafica.getId());
map.put("nomeCognome",anagrafica.getNome() + " " + anagrafica.getCognome());
map.put("indirizzo", "Indirizzo: " + anagrafica.getIndirizzo());
map.put("dataDiNascita", "Data Nascita: " + anagrafica.getDataDiNascita());
map.put("email", "Email: " + anagrafica.getEmail());
map.put("tipologieUtente", "Tipologie Utente: " + anagrafica.getTipologiaUtente());
map.put("aziendaCollegata", "Azienda Collegata: " + anagrafica.getAziendaCollegata());
map.put("telefono", "Telefono: " + anagrafica.getTelefono());
map.put("cellulare", "Cellulare: " + anagrafica.getCellulare());
map.put("interessi", "Interessi: " + anagrafica.getInteressi());
map.put("riferimenti", "Riferimenti" + anagrafica.getRiferimenti());
mylist.add(map);
Log.i("Dettagli", "D2");
return mylist;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(DettagliPagina.this);
progressDialog.setCancelable(true);
progressDialog.setMessage("Loading...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setProgress(0);
progressDialog.show();
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
final ListAdapter adapter = new SimpleAdapter(DettagliPagina.this, mylist, R.layout.dettagli,
new String[] { "nomeCognome", "dataDiNascita",
"tipologieUtente", "aziendaCollegata", "email",
"telefono", "cellulare", "interessi", "indirizzo",
"riferimenti" },
new int[] { R.id.tvNomeCognome, R.id.tvDataDiNascita,
R.id.tvTipologiaUtente, R.id.tvAziendaCollegata,
R.id.tvEmail, R.id.tvTelefono, R.id.tvCellulare,
R.id.tvInteressi, R.id.tvIndirizzo, R.id.tvRiferimenti });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), "ID '" + o.get("idAnagrafica") + "' was clicked.",
Toast.LENGTH_LONG).show();
}
});
progressDialog.dismiss();
}
}
public class PhoneCallListener extends PhoneStateListener {
private boolean isPhoneCalling = false;
String LOG_TAG = "LOGGING 123";
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (TelephonyManager.CALL_STATE_RINGING == state) {
// phone ringing
Log.i(LOG_TAG, "RINGING, number: " + incomingNumber);
}
if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
// active
Log.i(LOG_TAG, "OFFHOOK");
isPhoneCalling = true;
}
if (TelephonyManager.CALL_STATE_IDLE == state) {
// run when class initial and phone call ended, need detect flag
// from CALL_STATE_OFFHOOK
Log.i(LOG_TAG, "IDLE");
if (isPhoneCalling) {
Log.i(LOG_TAG, "restart app");
// restart app
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(
getBaseContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
isPhoneCalling = false;
}
}
}
}
}
here's the detail xml code:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/tvNomeCognome"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawableLeft="#drawable/icon"
android:drawablePadding="10dp"
android:padding="7dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="24dp" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="4dp" >
<TextView
android:id="#+id/tvTipologiaUtente"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="2dp"
android:textSize="20dp" />
<TextView
android:id="#+id/tvDataDiNascita"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="2dp"
android:textSize="18dp" />
<TextView
android:id="#+id/tvEmail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:autoLink="email"
android:linksClickable="true"
android:padding="2dp"
android:textSize="18dp" />
<TextView
android:id="#+id/tvTelefono"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:autoLink="phone"
android:linksClickable="true"
android:padding="2dp"
android:textSize="18dp" />
<TextView
android:id="#+id/tvCellulare"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:autoLink="phone"
android:linksClickable="true"
android:padding="2dp"
android:textSize="18dp" />
<TextView
android:id="#+id/tvInteressi"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="2dp"
android:textSize="18dp" />
<TextView
android:id="#+id/tvAziendaCollegata"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="2dp"
android:textSize="18dp" />
<TextView
android:id="#+id/tvIndirizzo"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="2dp"
android:textSize="18dp" />
<TextView
android:id="#+id/tvRiferimenti"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="2dp"
android:textSize="18dp" />
<Button
android:id="#+id/bCall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/chiama" />
</LinearLayout>
</LinearLayout>
</ScrollView>
Seems like you forgot to call setContentView(R.layout.your_layout); in your onCreate method
That button might not be part of the ListView, just of the main layout of that Activity.
If I understand what you're saying, you have a main view containing a ListView and a Button. If that affirmation is right, then you need to use an Activity instead of ListActivity or use :
mActivity= this ;
Button button = new Button(this);
button.setText("push me");
button.setLayoutParams(new AbsListView.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mActivity, "push", Toast.LENGTH_SHORT).show();
}
});
getListView().addFooterView(button);
Be sure to call addFooterView(View v) before setAdapter(ListAdapter adapter)
Instead of use OnClickListener, please try to use onItemClikListener.
You are in a ListActivity, so I think (maybe I'm wrong) that what you want is to make call with the selected row. So remove bCall and its onClickListener and try
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:3492395504"));
startActivity(callIntent);
}
});
You are getting an NPE because you are trying to do this:
bCall = (Button) findViewById(R.id.bCall);
When you haven't set a layout for the screen.
That button is in your list row layout so you need to set it's function in your list adapter.
If I'm understanding your code, you are kicking off an AsyncTask in onCreate, that sets the listAdaper within its onPostExecute method. Also, in onStart you are attempting to get the button bCall.
However, if onStart executes before your background task has completed, then you will not yet have set the adapter, thus your button will not exist and your call (Button) findViewById(R.id.bCall) will return null
Related
Hi I am working on the list view, I just want to set the values in the listview. I posted the code as below.As per SimpleAdapter It just shows the name of the content .I want to display the count also.But the count does not displayed and in the app it only shows name of the textview instead of the count. Please suggest me solution for the problem.I also attached the screenshot.
import java.util.ArrayList;
import android.R.*;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ActionBar;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class Folders extends navigation_drawer_class {
static final String NEW = "new", OVERDUE = "overdue", ASSIGNED = "assigned", TRASH = "trash", SPAM = "spam", NAME = "name", COUNT = "count";
ListView folders_list;
String[] folders;
String[] filter_id = {
"2",
"3",
"4",
"5",
"6"
};
List < String > folder_count;
JSONArray quick_view_array;
JSONObject quick_view_obj, count_obj;
String new_count, overdue_count, assigned_count, trash_count, spam_count;
List < HashMap < String, String >> menuItems;
Dialog dialog;
String URL;
Operation op = new Operation();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//setContentView(R.layout.folders);
new getbrand().execute();
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
//-----------------------
getLayoutInflater().inflate(R.layout.folders, frameLayout);
mDrawerList.setItemChecked(position, true);
setTitle(listArray[position]);
//------------------------
if (Operation.isNetworkAvailable(this)) {
folders_list = (ListView) findViewById(R.id.folder_display_list);
new folders().execute();
folders_list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView << ? > parent, View view, int position, long id) {
// TODO Auto-generated method stub
String fid = filter_id[position];
String title = folders[position];
Intent i = new Intent(Folders.this, Tickets.class);
i.putExtra("filter_id", "&vis_filter_id=" + fid);
i.putExtra("title", title);
i.putExtra("set_queue", "no");
startActivity(i);
}
});
} else {
Operation.showToast(getApplicationContext(), R.string.no_network);
}
}
private class folders extends AsyncTask < Void, Void, JSONArray > {
Dialog dialog;
#Override
public void onPreExecute() {
dialog = new Dialog(Folders.this, android.R.style.Theme_Translucent_NoTitleBar);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.progressbar);
dialog.show();
}
#Override
protected JSONArray doInBackground(Void...params) {
// TODO Auto-generated method stub
URL = op.getUrl(getApplicationContext(), "ticket", "quick_view", "");
quick_view_array = JSONfunctions.getJSONfromURL(URL + "&vis_encode=json", Folders.this);
return quick_view_array;
}
#Override
public void onPostExecute(JSONArray quick_view_array) {
super.onPostExecute(quick_view_array);
try {
quick_view_obj = quick_view_array.getJSONObject(0);
count_obj = quick_view_obj.getJSONObject("count");
folder_count = new ArrayList < String > ();
folder_count.add(count_obj.getString(NEW));
folder_count.add(count_obj.getString(OVERDUE));
folder_count.add(count_obj.getString(ASSIGNED));
folder_count.add(count_obj.getString(TRASH));
folder_count.add(count_obj.getString(SPAM));
folders = getResources().getStringArray(R.array.folders);
menuItems = new ArrayList < HashMap < String, String >> ();
for (int i = 0; i < filter_id.length; i++) {
HashMap < String, String > map = new HashMap < String, String > ();
map.put(NAME, folders[i]);
map.put(COUNT, folder_count.get(i));
menuItems.add(map);
}
SimpleAdapter list = new SimpleAdapter(Folders.this,
menuItems,
R.layout.folders,
new String[] {
NAME,
COUNT
},
new int[] {
R.id.folder_name, R.id.folder_count
}
);
folders_list.setAdapter(list);
dialog.dismiss();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
String filter_id = null, Tickets_title = null;
int start_limit = 0, page_no = 1;
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.menu_inbox:
Intent inbox = new Intent(Folders.this, Tickets.class);
inbox.putExtra("filter_id", "&vis_filter_id=1");
inbox.putExtra("title", "Inbox");
inbox.putExtra("set_queue", "no");
startActivity(inbox);
return true;
case R.id.menu_new_ticket:
Intent new_ticket = new Intent(Folders.this, New_Ticket_step1.class);
startActivity(new_ticket);
return true;
case R.id.menu_ticket_queue:
Intent ticket_queue = new Intent(Folders.this, Queues.class);
ticket_queue.putExtra("set_queue", "set");
startActivity(ticket_queue);
return true;
case R.id.menu_clients:
Intent clients = new Intent(Folders.this, Client.class);
startActivity(clients);
return true;
/* case R.id.menu_blabby:
Intent blabby = new Intent(Folders.this,Blabby.class);
blabby.putExtra("operation","get_blabs");
blabby.putExtra("filter","");
blabby.putExtra("title",(String)getString(R.string.blabs));
startActivity(blabby);
return true; */
//-------- Added for separate page
case R.id.menu_pin:
Intent pin = new Intent(Folders.this, Pinned_items.class);
startActivity(pin);
return true;
//-------- Added for separate page
case R.id.menu_settings:
Intent settings = new Intent(Folders.this, Settings.class);
startActivity(settings);
return true;
case R.id.menu_ticket_search:
Intent search = new Intent(Folders.this, Search.class);
search.putExtra("set_queue", "no");
startActivity(search);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
moveTaskToBack(true);
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
this.finish();
}
private class getbrand extends AsyncTask < Void, Void, JSONArray > {
Dialog dialog;
#Override
public void onPreExecute() {
dialog = new Dialog(Folders.this, android.R.style.Theme_Translucent_NoTitleBar);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.progressbar);
dialog.show();
}
#Override
protected JSONArray doInBackground(Void...params) {
// TODO Auto-generated method stub
String access = op.getUrl(getApplicationContext(), "ticket", "get_branding", "");
JSONArray access_denied = JSONfunctions.getJSONfromURL(access + "&vis_encode=json", Folders.this);
return access_denied;
}
#Override
public void onPostExecute(JSONArray access_denied) {
super.onPostExecute(access_denied);
String access_result = access_denied.toString();
ActionBar ab = getActionBar();
if (access_result.equals("[\"1\"]")) {
ab.setTitle(R.string.app_name);
ab.setIcon(R.drawable.application_icon);
// ab.setDisplayShowTitleEnabled(false);
// ab.setDisplayShowHomeEnabled(false);
// ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ffffff")));
} else {
ab.setTitle(R.string.nobrand_app_name);
ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ffffff")));
ab.setIcon(R.drawable.white3);
}
dialog.dismiss();
}
}
}
XML:
<?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="match_parent"
android:orientation="horizontal"
android:padding="3dp"
android:weightSum="100">
<TextView
android:id="#+id/folder_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_weight="30"
android:text="TextView"
android:textColor="#115c28"
android:textSize="15dp" />
<TextView
android:id="#+id/folder_count"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginRight="10dp"
android:layout_weight="70"
android:gravity="center"
android:text="0"
android:textColor="#115c28"
android:textSize="20dp"
android:textStyle="bold" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="35dp"
android:orientation="vertical">
<ListView
android:id="#+id/folder_display_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="3dp"
android:weightSum="100">
<TextView
android:id="#+id/folder_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
The first textview takes up the full width of the horizontal LinearLayout so you can't see the second textview.
You can see the count by making the width of the textviews wrap_content but it probably won't match the design you're trying to achieve.
Hi i just chage the xml template as follows.
<?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="match_parent"
android:layout_gravity="top"
android:orientation="vertical"
android:weightSum="100"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<!-- -->
<TextView
android:id="#+id/folder_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingLeft="30dip"
android:textSize="15dp"
android:layout_weight="1"
android:textColor="#115c28"/>
<TextView
android:id="#+id/folder_count"
android:layout_width="0dp"
android:layout_height="60dp"
android:textSize="20dp"
android:textStyle="bold"
android:textColor="#115c28"
android:gravity="center"
android:paddingRight="30dip"
android:paddingLeft="35dip"
android:layout_weight="1" />
<!-- -->
</LinearLayout>
<ListView
android:id="#+id/folder_display_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
Its working properly now.
I have a fragment class in with I am having few fragment tabs. each of them are opening another dedicated fragment. but I want to change one fragment to open an activity class. I have gone through many examples but didn't the problem solve. everytime my application goes crashed.
here is my fragment class.
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.appdupe.flamer.LoginUsingFacebook;
import com.appdupe.flamer.LoginUsingFacebook.BackGroundTaskForFetchingDataFromFaceBook;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.androidquery.AQuery;
import com.androidquery.callback.ImageOptions;
import com.appdupe.androidpushnotifications.ChatActivity;
import com.appdupe.flamer.QuestionsActivity;
import com.appdupe.flamer.pojo.LikeMatcheddataForListview;
import com.appdupe.flamer.pojo.LikedMatcheData;
import com.appdupe.flamer.pojo.Likes;
import com.appdupe.flamer.utility.AlertDialogManager;
import com.appdupe.flamer.utility.AppLog;
import com.appdupe.flamer.utility.ConnectionDetector;
import com.appdupe.flamer.utility.Constant;
import com.appdupe.flamer.utility.ScalingUtilities;
import com.appdupe.flamer.utility.ScalingUtilities.ScalingLogic;
import com.appdupe.flamer.utility.SessionManager;
import com.appdupe.flamer.utility.Ultilities;
import com.appdupe.flamer.utility.Utility;
import com.appdupe.flamerchat.db.DatabaseHandler;
import com.appdupe.flamernofb.R;
import com.google.gson.Gson;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu.OnOpenListener;
public class MainActivity extends SherlockFragmentActivity implements
OnClickListener, OnOpenListener {
// MainLayout mLayout;
private static final String TAG = "MainActivity";
private ListView matcheslistview;
Button btMenu;
private Button buttonRightMenu;
TextView tvTitle;
private Typeface topbartextviewFont;
private Editor editor;
private SharedPreferences preferences;
private EditText etSerchFriend;
double mLatitude = 0;
double mLongitude = 0;
double dLatitude = 0;
double dLongitude = 0;
// private Session.StatusCallback statusCallback = new
// SessionStatusCallback();
private Dialog mdialog;
// private boolean usersignup = false;
private boolean isProfileclicked = false;
private ArrayList<LikeMatcheddataForListview> arryList;
private MatchedDataAdapter adapter;
private ImageView profileimage;
private LinearLayout profilelayout, homelayout, messages, settinglayout,
invitelayout, questionLayout;
public SlidingMenu menu;
private boolean flagforHome, flagForProfile, flagForsetting;
// private AQuery aQuery;
private ImageOptions options;
private ConnectionDetector cd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// mLayout = (MainLayout)
// this.getLayoutInflater().inflate(R.layout.slidmenuxamplemainactivity,
// null);
// setContentView(mLayout);
cd = new ConnectionDetector(this);
preferences = PreferenceManager.getDefaultSharedPreferences(this);
editor = preferences.edit();
// aQuery = new AQuery(this);
options = new ImageOptions();
options.fileCache = true;
options.memCache = true;
setContentView(R.layout.slidmenuxamplemainactivity);
if (preferences.getBoolean(Constant.PREF_ISFIRST, true)) {
editor.putBoolean(Constant.PREF_ISFIRST, false);
editor.commit();
//startActivity(new Intent(this, QuestionsActivity.class));
}
tvTitle = (TextView) findViewById(R.id.activity_main_content_title);
topbartextviewFont = Typeface.createFromAsset(getAssets(),
"fonts/HelveticaLTStd-Light.otf");
tvTitle.setTypeface(topbartextviewFont);
tvTitle.setTextColor(Color.rgb(255, 255, 255));
tvTitle.setTextSize(20);
menu = new SlidingMenu(this);
menu.setMode(SlidingMenu.LEFT_RIGHT);
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
menu.setShadowWidthRes(R.dimen.shadow_width);
menu.setShadowDrawable(R.drawable.shadow);
menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
menu.setFadeDegree(0.35f);
menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
Log.d(TAG, "onCreate before add menu ");
menu.setMenu(R.layout.leftmenu);
menu.setSecondaryMenu(R.layout.rightmenu);
Log.d(TAG, "onCreate add menu ");
menu.setSlidingEnabled(true);
Log.d(TAG, "onCreate finish");
// search
etSerchFriend = (EditText) menu
.findViewById(R.id.et_serch_right_side_menu);
// btnSerch = (Button) menu.findViewById(R.id.btn_serch_right_side);
View leftmenuview = menu.getMenu();
View rightmenuview = menu.getSecondaryMenu();
initLayoutComponent(leftmenuview, rightmenuview);
menu.setSecondaryOnOpenListner(this);
// lvMenuItems = getResources().getStringArray(R.array.menu_items);
// lvMenu.setAdapter(new
// ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,
// lvMenuItems));
matcheslistview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// logDebug("setOnItemClickListener onItemClick arg2 "+arg2);
LikeMatcheddataForListview matcheddataForListview = (LikeMatcheddataForListview) arg0
.getItemAtPosition(arg2);
String faceboolid = matcheddataForListview.getFacebookid();
// logDebug(" background setOnItemClickListener onItemClick friend facebook id faceboolid "+faceboolid);
// logDebug(" background setOnItemClickListener onItemClick user facebook id faceboolid"+new
// SessionManager(MainActivity.this).getFacebookId());
Bundle mBundle = new Bundle();
mBundle.putString(Constant.FRIENDFACEBOOKID, faceboolid);
mBundle.putString(Constant.CHECK_FOR_PUSH_OR_NOT, "1");
Intent mIntent = new Intent(MainActivity.this,
ChatActivity.class);
mIntent.putExtras(mBundle);
startActivity(mIntent);
menu.toggle();
}
});
buttonRightMenu = (Button) findViewById(R.id.button_right_menu);
btMenu = (Button) findViewById(R.id.button_menu);
btMenu.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Show/hide the menu
toggleMenu(v);
}
});
try {
profilelayout.setOnClickListener(this);
homelayout.setOnClickListener(this);
messages.setOnClickListener(this);
settinglayout.setOnClickListener(this);
invitelayout.setOnClickListener(this);
questionLayout.setOnClickListener(this);
} catch (Exception e) {
AppLog.handleException("oncreate Exception ", e);
}
// Bundle extras = getIntent().getExtras();
System.out.println("Get Intent done");
try {
FragmentManager fm = MainActivity.this.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
FindMatches fragment = new FindMatches();
ft.add(R.id.activity_main_content_fragment, fragment);
tvTitle.setText(getResources().getString(R.string.app_name));
ft.commit();
setProfilePick(profileimage);
} catch (Exception e) {
AppLog.handleException("onCreate Exception ", e);
}
Ultilities mUltilities = new Ultilities();
int imageHeightAndWidht[] = mUltilities
.getImageHeightAndWidthForAlubumListview(this);
arryList = new ArrayList<LikeMatcheddataForListview>();
adapter = new MatchedDataAdapter(this, arryList, imageHeightAndWidht);
matcheslistview.setAdapter(adapter);
// final SessionManager sessionManager = new SessionManager(this);
buttonRightMenu.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (isProfileclicked) {
Intent mIntent = new Intent(MainActivity.this,
EditProfileNew.class);
startActivity(mIntent);
} else {
toggleRightMenu(v);
}
}
});
initSerchData();
}
private void initSerchData() {
etSerchFriend.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s.toString().trim());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public void setMenuTouchFullScreenEnable(boolean isEnable) {
if (isEnable) {
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
} else {
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
}
}
#Override
public void onOpen() {
AppLog.Log(TAG, "onOpen");
findLikedMatched();
}
#Override
protected void onResume() {
super.onResume();
AppLog.Log(TAG, " MainActivity onResume called");
}
private void setProfilePick(final ImageView userProfilImage) {
final Ultilities mUltilities = new Ultilities();
new Thread(new Runnable() {
#Override
public void run() {
final Bitmap bitmapimage = Utility.getBitmapFromURL(preferences
.getString(Constant.PREF_PROFILE_IMAGE_ONE, ""));
runOnUiThread(new Runnable() {
#Override
public void run() {
AppLog.Log(
TAG,
"Profile Image Url:"
+ preferences
.getString(
Constant.PREF_PROFILE_IMAGE_ONE,
""));
Bitmap cropedBitmap = null;
ScalingUtilities mScalingUtilities = new ScalingUtilities();
Bitmap mBitmap = null;
if (bitmapimage != null) {
cropedBitmap = mScalingUtilities
.createScaledBitmap(bitmapimage, 80, 80,
ScalingLogic.CROP);
bitmapimage.recycle();
mBitmap = mUltilities.getCircleBitmap(cropedBitmap,
1);
cropedBitmap.recycle();
userProfilImage.setImageBitmap(mBitmap);
// aQuery.id(userProfilImage).image(mBitmap);
} else {
}
}
});
}
}).start();
}
private void initLayoutComponent(View leftmenu, View rightmenu) {
matcheslistview = (ListView) rightmenu
.findViewById(R.id.menu_right_ListView);
profileimage = (ImageView) leftmenu.findViewById(R.id.profileimage);
profilelayout = (LinearLayout) leftmenu
.findViewById(R.id.profilelayout);
homelayout = (LinearLayout) leftmenu.findViewById(R.id.homelayout);
messages = (LinearLayout) leftmenu.findViewById(R.id.messages);
settinglayout = (LinearLayout) leftmenu
.findViewById(R.id.settinglayout);
invitelayout = (LinearLayout) leftmenu.findViewById(R.id.invitelayout);
/*questionLayout = (LinearLayout) leftmenu
.findViewById(R.id.questionLayout);*///devraj
}
private void findLikedMatched() {
AppLog.Log(TAG, "findLikedMatched");
String params[] = { preferences.getString(Constant.FACEBOOK_ID, "") };
new BackgroundTaskForFindLikeMatched().execute(params);
}
private class BackgroundTaskForFindLikeMatched extends
AsyncTask<String, Void, Void> {
private Ultilities mUltilities = new Ultilities();
private List<NameValuePair> getuserparameter;
private String likedmatchedata;
private LikedMatcheData matcheData;
private ArrayList<Likes> likesList;
private LikeMatcheddataForListview matcheddataForListview;
DatabaseHandler mDatabaseHandler = new DatabaseHandler(
MainActivity.this);
private boolean isResponseSuccess = true;
#Override
protected Void doInBackground(String... params) {
try {
File appDirectory = mUltilities
.createAppDirectoy(getResources().getString(
R.string.appdirectory));
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground appDirectory "
+ appDirectory);
File _picDir = new File(appDirectory, getResources().getString(
R.string.imagedirematchuserdirectory));
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground ");
getuserparameter = mUltilities.getUserLikedParameter(params);
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground getuserparameter "
+ getuserparameter);
likedmatchedata = mUltilities.makeHttpRequest(
Constant.getliked_url, Constant.methodeName,
getuserparameter);
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground likedmatchedata "
+ likedmatchedata);
Gson gson = new Gson();
matcheData = gson.fromJson(likedmatchedata,
LikedMatcheData.class);
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground matcheData "
+ matcheData);
if (matcheData.getErrFlag() == 0) {
likesList = matcheData.getLikes();
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground likesList "
+ likesList);
if (arryList != null) {
arryList.clear();
}
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched doInBackground likesList sized "
+ likesList.size());
for (int i = 0; i < likesList.size(); i++) {
matcheddataForListview = new LikeMatcheddataForListview();
String userName = likesList.get(i).getfName();
String facebookid = likesList.get(i).getFbId();
String picturl = likesList.get(i).getpPic();
int falg = likesList.get(i).getFlag();
String latd = likesList.get(i).getLadt();
matcheddataForListview.setFacebookid(facebookid);
matcheddataForListview.setUserName(userName);
matcheddataForListview.setImageUrl(picturl);
matcheddataForListview.setFlag("" + falg);
matcheddataForListview.setladt(latd);
File imageFile = mUltilities.createFileInSideDirectory(
_picDir, userName + facebookid + ".jpg");
Utility.addBitmapToSdCardFromURL(likesList.get(i)
.getpPic().replaceAll(" ", "%20"), imageFile);
matcheddataForListview.setFilePath(imageFile
.getAbsolutePath());
if (!preferences.getString(Constant.FACEBOOK_ID, "")
.equals(facebookid)) {
arryList.add(matcheddataForListview);
}
}
DatabaseHandler mDatabaseHandler = new DatabaseHandler(
MainActivity.this);
ArrayList<LikeMatcheddataForListview> arryListtem = mDatabaseHandler
.getUserFindMatch();
AppLog.Log(TAG, "arryListtem " + arryListtem);
if (arryListtem != null && arryListtem.size() > 0) {
AppLog.Log(TAG, "arryList size " + arryListtem.size());
arryList.clear();
arryList.addAll(arryListtem);
mUltilities.showImage
}
}
// "errNum": "50",
// "errFlag": "1",
// "errMsg": "Sorry, no matches found!"
else if (matcheData.getErrFlag() == 1) {
ArrayList<LikeMatcheddataForListview> arryListtem = mDatabaseHandler
.getUserFindMatch();
AppLog.Log(TAG, "arryListtem " + arryListtem);
if (arryListtem != null && arryListtem.size() > 0) {
AppLog.Log(TAG, "arryList size " + arryListtem.size());
arryList.clear();
arryList.addAll(arryListtem);
}
} else {
}
} catch (Exception e) {
AppLog.handleException(
"BackgroundTaskForFindLikeMatched doInBackground Exception ",
e);
isResponseSuccess = false;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
AppLog.Log(TAG, "BackgroundTaskForFindLikeMatched onPostExecute ");
try {
mdialog.dismiss();
} catch (Exception e) {
AppLog.Log(TAG,
"BackgroundTaskForFindLikeMatched onPostExecute Exception "
+ e);
}
if (!isResponseSuccess) {
AlertDialogManager.errorMessage(MainActivity.this, "Alert",
"Request timeout");
}
adapter.notifyDataSetChanged();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
AppLog.Log(TAG, "BackgroundTaskForFindLikeMatched onPreExecute ");
try {
mdialog = mUltilities.GetProcessDialog(MainActivity.this);
mdialog.setCancelable(false);
mdialog.show();
} catch (Exception e) {
AppLog.handleException(
"BackgroundTaskForFindLikeMatched onPreExecute Exception ",
e);
}
}
}
private class MatchedDataAdapter extends
ArrayAdapter<LikeMatcheddataForListview> {
private AQuery aQuery;
private Activity mActivity;
private LayoutInflater mInflater;
private SessionManager sessionManager;
public MatchedDataAdapter(Activity context,
List<LikeMatcheddataForListview> objects,
int imageHeigthAndWidth[]) {
super(context, R.layout.matchedlistviewitem, objects);
mActivity = context;
mInflater = (LayoutInflater) mActivity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// this.imageHeigthAndWidth=imageHeigthAndWidth;
sessionManager = new SessionManager(context);
aQuery = new AQuery(context);
}
#Override
public int getCount() {
return super.getCount();
}
#Override
public LikeMatcheddataForListview getItem(int position) {
return super.getItem(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.matchedlistviewitem,
null);
holder.imageview = (ImageView) convertView
.findViewById(R.id.userimage);
holder.textview = (TextView) convertView
.findViewById(R.id.userName);
holder.lastMasage = (TextView) convertView
.findViewById(R.id.lastmessage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textview.setId(position);
holder.imageview.setId(position);
holder.lastMasage.setId(position);
holder.textview.setText(getItem(position).getUserName());
aQuery.id(holder.imageview).image(getItem(position).getImageUrl());
try {
holder.lastMasage.setText(sessionManager
.getLastMessage(getItem(position).getFacebookid()));
} catch (Exception e) {
AppLog.handleException(TAG + " getView Exception ", e);
}
return convertView;
}
class ViewHolder {
ImageView imageview;
TextView textview;
TextView lastMasage;
}
}
public void toggleMenu(View v) {
menu.toggle();
}
public void toggleRightMenu(View v) {
menu.showSecondaryMenu();
}
#Override
public void onBackPressed() {
if (menu.isMenuShowing()) {
menu.toggle();
} else if (menu.isSecondaryMenuShowing()) {
menu.showSecondaryMenu();
} else {
super.onBackPressed();
}
}
#Override
public void onStop() {
super.onStop();
if (mdialog != null) {
mdialog.dismiss();
mdialog = null;
}
}
#Override
protected void onDestroy() {
if (mdialog != null && mdialog.isShowing()) {
mdialog.dismiss();
}
super.onDestroy();
}
#Override
public void onClick(View v) {
FragmentManager fm = MainActivity.this.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment fragment = null;
if (v.getId() == R.id.homelayout) {
if (!cd.isConnectingToInternet()) {
Toast.makeText(this, "No Internet", Toast.LENGTH_SHORT).show();
return;
}
if (flagforHome) {
menu.toggle();
return;
} else {
fragment = new FindMatches();
buttonRightMenu
.setBackgroundResource(R.drawable.selector_for_message_button);
tvTitle.setText(getResources().getString(R.string.app_name));
flagforHome = true;
flagForProfile = false;
flagForsetting = false;
isProfileclicked = false;
if (fragment != null) {
ft.replace(R.id.activity_main_content_fragment, fragment);
ft.commit();
}
menu.toggle();
}
} else if (v.getId() == R.id.profilelayout) {
if (!cd.isConnectingToInternet()) {
Toast.makeText(this, "No Internet", Toast.LENGTH_SHORT).show();
return;
}
if (flagForProfile) {
menu.toggle();
return;
} else {
buttonRightMenu.setBackgroundResource(R.drawable.edit_btn);
isProfileclicked = true;
fragment = new UserProfile();
tvTitle.setText(getResources().getString(R.string.myprofile));
flagforHome = false;
flagForProfile = true;
flagForsetting = false;
if (fragment != null) {
ft.replace(R.id.activity_main_content_fragment, fragment);
ft.commit();
}
menu.toggle();
}
}
else if (v.getId() == R.id.settinglayout) {
if (!cd.isConnectingToInternet()) {
Toast.makeText(this, "No Internet", Toast.LENGTH_SHORT).show();
return;
}
if (flagForsetting) {
menu.toggle();
return;
} else {
buttonRightMenu
.setBackgroundResource(R.drawable.selector_for_message_button);
tvTitle.setText(getResources().getString(R.string.settings));
fragment = new SettingActivity();
flagforHome = false;
flagForProfile = false;
flagForsetting = true;
flagForInvite=false;
isProfileclicked = false;
/*if (fragment != null) {
ft.replace(R.id.activity_main_content_fragment, fragment);
ft.commit();
// tvTitle.setText(selectedItem);
}*/
menu.toggle();
/*Intent setIntent = new Intent(getApplicationContext(),Setting2.class);
startActivity(setIntent);*/
}
}
///devraj
else if (v.getId() == R.id.messages) {
if (!cd.isConnectingToInternet()) {
Toast.makeText(this, "No Internet", Toast.LENGTH_SHORT).show();
return;
}
toggleRightMenu(v);
} /*else if (v.getId() == R.id.questionLayout) {
if (!cd.isConnectingToInternet()) {
Toast.makeText(this, "No Internet", Toast.LENGTH_SHORT).show();
return;*/
/*}
menu.toggle();
Intent questionIntent = new Intent(this, QuestionsActivity.class);
startActivity(questionIntent);*/
//}
else if (v.getId() == R.id.invitelayout) {
if (!cd.isConnectingToInternet()) {
Toast.makeText(this, "No Internet", Toast.LENGTH_SHORT).show();
return;
}
// Change by Dilavar
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent
.putExtra(
Intent.EXTRA_TEXT,
"I am using Flamer App ! Why don't you try it out...\nInstall Flamer now !\nhttps://play.google.com/store/apps/details?id=com.appdupe.flamernofb");
sendIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
" Flamer App !");
sendIntent.setType("message/rfc822"); //
sendIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
new String[] { " info#appdupe.com" });
startActivity(Intent
.createChooser(sendIntent, "Send mail using..."));
}
/*settinglayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent mintent = new Intent(getApplicationContext(),Setting2.class);
startActivity(mintent);
}
});*/
}
}
I want Setting tab to open a new activity not fragment that is Setting2
here is my activity class that I have to open
import android.app.Activity;
import android.os.Bundle;
public class Setting2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.setting2);
}
}
Here is my layout , I am posting it here as it so long and don't have permission to post more lines in question.
<?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="match_parent"
android:orientation="vertical"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#088A08" >
<Button
android:id="#+id/button_menu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:background="#drawable/selector_for_menu_button"
android:onClick="toggleMenu" />
<TextView
android:id="#+id/activity_main_content_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Toker" />
<Button
android:id="#+id/button_right_menu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:background="#drawable/selector_for_message_button"
android:onClick="rightmenu" />
</RelativeLayout>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="150dp"
android:background="#088A08" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#088A08" >
<ImageView
android:id="#+id/imagev1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/btn_add_photo"
android:gravity="center_horizontal" />
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout1"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:background="#088A08"
android:gravity="center_horizontal"
android:text="View My Profile" />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="5.0">
<RelativeLayout
android:id="#+id/lin1"
android:layout_width="fill_parent"
android:layout_weight="1.0"
android:background="#ffffff"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView1"
android:layout_alignTop="#+id/imageView1"
android:layout_marginBottom="9dp"
android:layout_marginLeft="21dp"
android:layout_toRightOf="#+id/imageView1"
android:text="Discovery Settings"
android:textSize="12dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView1"
android:layout_alignLeft="#+id/textView1"
android:text="Change who you see" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="12dp"
android:background="#drawable/pref" />
<Button
android:id="#+id/morebtn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView1"
android:layout_marginRight="20dp"
android:background="#drawable/more" />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#color/black"
android:orientation="horizontal"/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_weight="1.0"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="12dp"
android:background="#drawable/settings" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/imageView2"
android:layout_marginLeft="23dp"
android:layout_toRightOf="#+id/imageView2"
android:text="App Settings"
android:textSize="12dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView2"
android:layout_alignLeft="#+id/textView3"
android:text="Notification and Resource" />
<Button
android:id="#+id/morebtn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView3"
android:layout_marginRight="20dp"
android:background="#drawable/more" />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#color/black"
android:orientation="horizontal"/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_weight="1.0"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imageView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="12dp"
android:background="#drawable/filter" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView3"
android:layout_marginLeft="23dp"
android:layout_toRightOf="#+id/imageView3"
android:text="What are you into" />
<TextView
android:id="#+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView4"
android:layout_alignTop="#+id/imageView3"
android:text="Your Interest"
android:textSize="12dp" />
<Button
android:id="#+id/morebtn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView8"
android:layout_marginRight="20dp"
android:background="#drawable/more" />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#color/black"
android:orientation="horizontal"/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_weight="1.0"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imageView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="12dp"
android:background="#drawable/reachout" />
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView5"
android:layout_marginLeft="27dp"
android:layout_toRightOf="#+id/imageView5"
android:text="We want to hear it all" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView6"
android:layout_alignTop="#+id/imageView5"
android:text="Get in Touch"
android:textSize="12dp" />
<Button
android:id="#+id/morebtn4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView7"
android:layout_marginRight="20dp"
android:background="#drawable/more" />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#color/black"
android:orientation="horizontal"/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_weight="1.0"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imageView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="12dp"
android:background="#drawable/share" />
<Button
android:id="#+id/morebtn5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView5"
android:layout_marginRight="20dp"
android:background="#drawable/more" />
<TextView
android:id="#+id/textView9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/morebtn5"
android:layout_marginLeft="27dp"
android:layout_toRightOf="#+id/imageView4"
android:text="Help us spread the world" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView9"
android:layout_alignTop="#+id/imageView4"
android:text="Tell Your Friends"
android:textSize="12dp" />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#color/black"
android:orientation="horizontal"/>
</LinearLayout>
</LinearLayout>
Step 1
- declare your activity inside of the manifest
Step 2
- starActivity(new Intent(getAcivity(), MyClass.class));
Step 3
- post your logcat if this didn't help while it should !
Edit: the issue seems that you are not setting a height to your layouts, base on your layout that you posted you have five layouts that are missing android:layout_height please add that and force close shall be gone.
I have made an application in android,now i have made activities notes.xml,contactinfo.xml and an android xml file named listplaceholder5.xml,i need is i've changed the android:text of textview to "notes"in "listplaceholder5.xml" file which is used in note.java but it ,not displaying "notes" its displaying "contact".i have tried sode a sbelow:please help me to change the code so that i can solve it,
Note.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name: "
android:textColor="#000000"
android:textStyle="bold"
android:textSize="16sp"
android:paddingLeft="5dp"
/>
<TextView
android:id="#+id/item_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="item_title"
android:textColor="#000000"
android:textStyle="bold"
android:textSize="16sp"
android:paddingLeft="5dp"
android:ellipsize="end"
android:lines="1"
android:scrollHorizontally="true"
/>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<!--
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:text="#string/hello"
android:visibility="gone"
/>-->
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phone : "
android:textColor="#000000"
android:textSize="14sp"
android:paddingLeft="5dp"
/>
<TextView
android:id="#+id/item_subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="item_subtitle"
android:textColor="#000000"
android:textSize="14sp"
/>
<TextView
android:id="#+id/item_subtitle1"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="14sp"
android:layout_width="wrap_content"
android:ellipsize="end"
android:lines="1"
android:scrollHorizontally="true"
/>
<!-- New Layout -->
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:paddingRight="10dp"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/forward" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
listplaceholder5.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/detailpage">
<LinearLayout android:layout_width="fill_parent"
android:weightSum="1"
android:background="#drawable/bottombackground"
android:id="#+id/linearLayout1"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:textColor="#FFFFFF"
android:layout_marginLeft="18dp"
android:layout_weight="0.88"
android:textSize="18sp"
android:textStyle="bold"
android:id="#+id/textView1"
android:text="Notes"
android:gravity="center"
android:layout_gravity="center"
android:layout_height="wrap_content">
</TextView>
</LinearLayout>
<ListView
android:id="#id/android:list"
android:layout_height="wrap_content"
android:drawSelectorOnTop="false"
android:layout_width="fill_parent"
android:cacheColorHint="#00000000"
android:dividerHeight="2dp"
android:listSelector="#drawable/list_selector"
/>
<TextView
android:id="#id/android:empty"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="No data"/>
</LinearLayout>
NOteActivity.java
package com.hussain.realtylog;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.hussain.realtylog.Contact.DownloadWebPageTask;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
public class NoteActivity extends ListActivity {
JSONArray jArray = null;
JSONObject json_data = null;
String getMLSID =null;
TextView titl;
// Button btnBuyer;
// Button btnRental;
String getJson =null;
public String user=null;
public static String urlContact=null;
public static String jsonContact=null;
ArrayList<HashMap<String, String>> mylist;
private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
private ProgressDialog dialog;
#Override
protected String doInBackground(String... urls) {
user= TabBarExample.getJsonUser;
urlContact = StoreSession.strBaseURL+"&username="+user+"&act=ContactList";
if( StoreSession.FlagContact == 0){
boolean isNet = checkInternetConnection();
if(isNet==true){
jsonContact = JSONfunctions.getJSONfromURL(urlContact);
}else{
alertbox("Contact", "Please check your mobile network setting and try again.");
}
}
mylist = new ArrayList<HashMap<String, String>>();
try{
jArray = new JSONArray(jsonContact);
for(int i=0;i<jArray.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("ID", e.getString("ID"));
map.put("username", e.getString("username"));
map.put("email", e.getString("email"));
map.put("phone", e.getString("phone"));
map.put("phone2", e.getString("phone2"));
map.put("fullname", e.getString("fullname"));
map.put("address", e.getString("address"));
map.put("notes", e.getString("info"));
map.put("active", e.getString("active"));
map.put("created", e.getString("created"));
map.put("lastUpdate", e.getString("lastUpdate"));
map.put("guest", e.getString("guest"));
map.put("category", "Category: "+e.getString("category"));
mylist.add(map);
}
}catch(JSONException e){
// Log.e("log_tag", "Error parsing data "+e.toString());
}
return null;
}
#Override
protected void onPostExecute(String result) {
ListAdapter adapter = new SimpleAdapter(NoteActivity.this, mylist , R.layout.activity_note,
new String[] { "fullname", "phone" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
int[] colors = {0, 0xFFFF0000, 0}; // red for the example
lv.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
lv.setDividerHeight(1);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
final ProgressDialog dialog = ProgressDialog.show(NoteActivity.this, "Loading",
"Please wait...", true);
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
dialog.dismiss();
}
};
Thread checkUpdate = new Thread() {
#SuppressWarnings("unchecked")
public void run() {
HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);
final String strName= o.get("fullname").toString();
final String strEmail= o.get("email").toString();
final String Phone= o.get("phone").toString();
final String Phone2= o.get("phone2").toString();
getMLSID = o.get("notes").toString();
Intent newActivityFirst = new Intent(NoteActivity.this, ContactInfo.class);
newActivityFirst.putExtra("name", strName);
newActivityFirst.putExtra("strEmail", strEmail);
newActivityFirst.putExtra("phone", Phone);
newActivityFirst.putExtra("phone2", Phone2);
newActivityFirst.putExtra("notes", getMLSID);
NoteActivity.this.startActivity(newActivityFirst);
handler.sendEmptyMessage(0);
}
};
checkUpdate.start();
}
});
StoreSession.FlagContact=1;
//dialog.hide();
dialog.dismiss();
}
private ListView getListView() {
// TODO Auto-generated method stub
return null;
}
private void setListAdapter(ListAdapter adapter) {
// TODO Auto-generated method stub
}
protected void onPreExecute() {
dialog = new ProgressDialog(NoteActivity.this);
dialog.setCancelable(true);
dialog.setMessage("Please wait...");
dialog.show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note);
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute();
setContentView(R.layout.listplaceholder5);
TextView title=(TextView)findViewById(R.id.textView1);
title.setText("Notes");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
StoreSession.FlagListing =0;
StoreSession.FlagBuyer =0;
StoreSession.FlagRental =0;
StoreSession.FlagDocument =0;
StoreSession.FlagContact =0;
ActiveShowingInfo.flagActiveClickCheck =0;
Main.username.setText("");
Main.pwd.setText("");
return false;
}
return super.onKeyDown(keyCode, event);
}
protected void alertbox(String title, String mymessage)
{
new AlertDialog.Builder(this)
.setMessage(mymessage)
.setTitle(title)
.setCancelable(true)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){}
})
.show();
}
private boolean checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
return true;
} else {
//Log.v("tag", "Internet Connection Not Present");
return false;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_note, menu);
return true;
}
}
please help me to solve this problem.thanking you in advance.
after getting the title as follows:
title= (TextView) findViewById(R.id.item_title);
use setText method to set the title as you wish.
I think it will solve your problem.
I am working with the android support library, to be able to use fragments from Froyo, and the Sherlock extension, to show an ActionBar.
I have a fragment which shows three textViews and a button, and I want to be able to change the button text dinamically, depending on the content of the Intent. The problem is that when I call button.setText(String text), a second button appears. However, I've called button.getId() when clicking on each of them, and the Id is the same. I don't have a clue of why this is happening, so I'd appreciate some help.
The app is run on a Samsung Galaxy S, with Android 2.3.3. I can't upload a screen capture because I don't have enough reputation yet :(
This is the code:
FRAGMENT
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.actionbarsherlock.app.SherlockFragment;
import com.parse.ParseUser;
import com.tiempoderodar.egdf.EGDF_App;
import com.tiempoderodar.egdf.R;
import com.tiempoderodar.egdf.security.Constants;
/**
* #author Daniel Leal López
*
*/
public class ChapterDetailsFragment extends SherlockFragment{
private Button b;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("ChapterDetailsFragment", "Created");
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ParseUser user = EGDF_App.getUser();
b = (Button) getSherlockActivity().findViewById(R.id.buttonWatchChapter);
if (user != null){
String chapterNumber = "";
Bundle extras = getSherlockActivity().getIntent().getExtras();
String s = extras.getString(Constants.CHAPTER_NUMBER_PARSE);
if((s != null)&&(!s.equals(""))){
// tvNumber.setText(s);
chapterNumber = "Chapter_" + s;
Log.i("Properties", s);
}
String seen = user.getString(chapterNumber);
if((seen != null)&&(!seen.equals(""))&&(seen.equals(Constants.USER_CHAPTER_SEEN))){
b.setText("Second text: "+getString(R.string.watch_chapter_button_text));
Log.i("BUTTON CHANGED", "Text changed to watch");
}
else if((seen != null)&&(!seen.equals(""))&&(seen.equals(Constants.USER_CHAPTER_NOT_SEEN))){
b.setText("Second text: " + getString(R.string.buy_chapter_button_text));
Log.i("BUTTON CHANGED", "Text changed to buy");
}else{
Log.w("DEV ERROR", "Chapter text not obtained");
}
}else{
Log.w("DEV ERROR", "ParseUser is null in EGDF_App!!!");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.chapter_details, container, false);
return view;
}
public void setText(String item) {
getSherlockActivity().getSupportActionBar().setTitle(item);
}
public void setButtonText(String text){
b.setText(text);
}
}
Activity
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.actionbarsherlock.app.SherlockFragmentActivity;
public class ChapterDetailsActivity extends SherlockFragmentActivity {
private Bundle extras;
MediaPlayer mMediaPlayer;
private String chapterNumber;
private boolean isChapterSeen;
// private int duration;
#Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.Theme_Sherlock_Light_DarkActionBar);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chapter_details);
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
ChapterDetailsFragment details = new ChapterDetailsFragment();
details.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(
android.R.id.content, details).commit();
}
}
public void watchChapter(View view){
Log.i("Button", "Watch chapter button PRESSED");
Button b = (Button) view;
Log.d("BUTTON PARENT VIEW", b.getParent().getClass().getName());
Log.d("BUTTON ID", String.valueOf(b.getId()));
String loadChapter = getString(R.string.load_chapter_button_text);
String watchChapter = getString(R.string.watch_chapter_button_text);
String buyChapter = getString(R.string.buy_chapter_button_text);
}
#Override
protected void onPause() {
Log.i("Activity lifecycle", "On pause called");
super.onPause();
}
#Override
protected void onStop() {
Log.i("Activity lifecycle", "On stop called");
super.onStop();
}
#Override
protected void onDestroy() {
Log.i("Activity lifecycle", "On destroy called");
super.onDestroy();
EGDF_App.releaseMediaPlayer();
}
#Override
protected void onResume() {
Log.i("Activity lifecycle", "On resume called");
super.onResume();
}
#Override
protected void onStart() {
Log.i("Activity lifecycle", "On start called");
super.onStart();
}
}
Activity 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="match_parent" >
<fragment
android:id="#+id/chapterDetailsFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.tiempoderodar.egdf.content.ChapterDetailsFragment" />
</LinearLayout>
Fragment 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="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textViewChapterNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30dip" />
<TextView
android:id="#+id/textViewChapterSeason"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30dip" />
<TextView
android:id="#+id/textViewChapterSinopsis"
android:layout_width="wrap_content"
android:layout_height="0dip"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30dip" />
<TextView
android:id="#+id/textViewChapterCredits"
android:layout_width="wrap_content"
android:layout_height="0dip"
android:layout_weight="1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30dip" />
<Button
android:id="#+id/buttonWatchChapter"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/watch_chapter_button_text"
android:layout_gravity="center"
android:onClick="watchChapter"/>
</LinearLayout>
Thanks!
I think I might have found the problem. I was calling
b = (Button) getSherlockActivity().findViewById(R.id.button);
but it should be
b = (Button) getView().findViewById(R.id.button);
With that change it works correctly
I have two tabs and each tab is a Fragment. In one of the fragments (Afragment.claas) I have a dialog box to insert some data, and I want to save them in a database. When I fill the text fields and press OK, the application stops.
I think when I initialize the edittext there is something wrong.
name = (EditText) activity.findViewById(R.id.etProviderName);
The above statement is returning null
Here is my code:
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListFragment;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class Afragment extends ListFragment {
DBAdapter db;
Activity activity;
private static final String fields[] = { "provider._providerName", "_providerMobile" };
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initAdapter();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_add:
add();
return (true);
case R.id.menu_reset:
initAdapter();
return (true);
case R.id.menu_info:
Toast.makeText(activity, "Developed By Omar Al-Shammary", Toast.LENGTH_LONG)
.show();
return (true);
}
return (super.onOptionsItemSelected(item));
}
private void add() {
// TODO Auto-generated method stub
System.out.println("insider Add Method");
final View addView = activity.getLayoutInflater().inflate(R.layout.add_provider, null);
new AlertDialog.Builder(activity).setTitle("Add a Provider").setView(addView)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
System.out.println("Befor calling insert in providers");
insertInProviders();
System.out.println("after calling insert in providers");
}
}).setNegativeButton("Cancel", null).show();
initAdapter();
}
private void initAdapter() {
activity = getActivity();
db = new DBAdapter(activity);
fillTheList();
}
public void fillTheList()
{
db.open();
Cursor data = db.getAllProviders();
CursorAdapter dataSource = new SimpleCursorAdapter(activity,
R.layout.row, data, fields,
new int[] { R.id.first, R.id.last });
setListAdapter(dataSource);
db.close();
setListAdapter(dataSource);
}
public void insertInProviders()
{
EditText name,location,number;
name = (EditText) activity.findViewById(R.id.etProviderName);
location = (EditText) activity.findViewById(R.id.etProviderName);
number = (EditText) activity.findViewById(R.id.etProviderName);
if(name == null)
System.out.println("EditeText name is null");
String provName = name.getText().toString();
if(location == null)
System.out.println("location is null");
String provLocation = location.getText().toString();
String provNumber = number.getText().toString();
System.out.println("Before Open");
db.open();
System.out.println("Before DB.Insert");
db.insertProvider(provName, provLocation, provNumber);
System.out.println("Before Close");
db.close();
}
}
add_provider.xml
<?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="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tvProviderName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name" />
<EditText
android:id="#+id/etProviderName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/tvProvLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Location" />
<EditText
android:id="#+id/etProvLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" />
<TextView
android:id="#+id/tvProvNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number" />
<EditText
android:id="#+id/etProvNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" />
</LinearLayout>
This is the code I use for declaring buttons in Fragments - maybe it can help you.
What I would do is access the inflated layout and then you should be able to access items underneath it. Let me know if that makes sense.
LinearLayout theLayout = (LinearLayout)inflater.inflate(R.layout.tab_frag1_layout, container, false);
// Register for the Button.OnClick event
Button b = (Button)theLayout.findViewById(R.id.frag1_button);
#Override
public void onClick(View v) {
Toast.makeText(Tab1Fragment.this.getActivity(), "OnClickMe button clicked", Toast.LENGTH_LONG).show();
}
});
return theLayout;
So maybe you should try this since you inflate your View as "addView"
name = (EditText) addView.findViewById(R.id.etProviderName);
The findViewById should not be called by the activity but by the enclosing view. You should have something like:
In the class
View aView;
In the method:
LayoutInflater inflater = getActivity().getLayoutInflater();
aView = inflater.inflate(R.layout.add_provider, null);
...
EditText name = (EditText) aView.findViewById(R.id.etProviderName);
I hope it helps.