Can anyone help me with this. I want to send data from edittext to another activity in the JSONMessage. I want to send to the IDDevice in my second activity.
Here is my code
It's my firstActivity
et = (EditText) findViewById(R.id.editText1);
bt = (Button) findViewById(R.id.bAdd);
lv = (ListView) findViewById(R.id.listView);
arrayList = new ArrayList<String>();
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, arrayList);
lv.setAdapter(adapter);
onButtonClick();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String inputID = et.getText().toString();
Intent IDdevice = new Intent(MainActivity.this, ControlLed.class);
IDdevice.putExtra("ID", inputID);
startActivity(IDdevice);
}
});
}
And second activity
public void device1on(){
String topic = "server/esp001";
MqttMessage message = new MqttMessage();
message.setPayload("{\"idDevice\":\"esp001\",\"status\":\"0\",\"data\":\"100\",\"address\":\"1\",\"function\":\"1\",\"user\":\"admin\"}".getBytes());// I want to send data from first activity to the idDevice
try {
client.publish(topic, message);
} catch (MqttException e) {
e.printStackTrace();
}
}
In second activity, get id from Intent using getStringExtra method as mentioned below:
String id = getIntent().getStringExtra("ID");
And then set it to message object
JSONObject json = new JSONObject();
try {
json.put("idDevice", id);
json.put("status", "0");
json.put("data", "100");
json.put("address", "1");
json.put("function", "1");
json.put("user", "admin");
} catch (JSONException e) {
}
String payload = json.toString(); //"{\"idDevice\":\"value of id\",\"status\":\"0\",\"data\":\"100\",\"address\":\"1\",\"function\":\"1\",\"user\":\"admin\"}"
message.setPayload(payload.getBytes());
String getvallue;
Intent i=i.getIntent();
getVallue=i.getStringExtra("name");
Textview txt=(Textview)findviewbyid(R.id.txt);
txt.setText(getVallue);
Related
I have a list view in Main activity, I have fill some values in it by using Array Adapter
String[] arr = new String[]{"Android ListView Item 1", "Android ListView Item 2",
"Simple List View In Android", "List View onClick Event","Android List View OnItemClickListener",
"Open New Activity When ListView item Clicked", "List View onClick Source Code", "List View Array Adapter Item Click",
};
Now I want to set onclickListener to each item of the list. I am requesting an api which gives me jsonresponse and I want to iterate over jsonresponse and send required data to another activity when click item of the list.
I tried with following:
ArrayAdapter<String> arrayadapter = new ArrayAdapter<String>(this,
R.layout.activity_main2, R.id.textview, arr);
listview.setAdapter(arrayadapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String textToPass = "hello";
if (position == 0) {
Bundle passData = new Bundle();
passData.putString("data",textToPass);
Intent myIntent = new Intent(view.getContext(), Main2Activity.class);
myIntent.putExtras(passData);
startActivity(myIntent);
}
}
});
}
private String jsonParse(){
String url = "//testing/api.php"; //get json response locally
RequestQueue requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
JSONArray jsonArray = null;
try {
jsonArray = response.getJSONArray("Item");
for(int i=0; i<=jsonArray.length();i++){
HashMap<String,String> dict = new HashMap<String,String>();
JSONObject tv = jsonArray.getJSONObject(i);
String sid;
dict.put("cid", tv.getString("sid") );
// String cid = tv.getString("sid");
String categoryName =tv.getString("category_name");
String baseUrl = "//testing/";
String imageUrl = baseUrl + tv.getString("category_image");
//textView.append(cid + "," + categoryName + "," + imageUrl + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
assert jsonArray != null;
Log.d("Main",jsonArray.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(error.getMessage(), "utf-8");
}
});
requestQueue.add(jsonObjectRequest);
Please help
If I understood properly then I think you want to send HashMap dic to another activity. HashMap are serializable this means you can easily pass it in intent, moreover both key and value are string which are also serializable
intent.putExtra("dic.key", dic);
And in your next activity retrieve it with typecasting.. simple
HashMap<String, String> hashMap = (HashMap<String, String>) intent.getSerializableExtra("hashMap");
I am a beginner developer who is studying Android.
The function I want to develop is "Save the data entered in EditText as JSON, save it as SharedPreference, and output it to ListView".
To save it as SharedPreference is OK, but, To output it to ListView is not working now.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private ListView listView;
private Button save_btn;
private ArrayList<List> data = new ArrayList<List>();
ListAdapter adapter;
String title="";
String info="";
int img = R.drawable.man;
String jsondata;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
save_btn = (Button) findViewById(R.id.button1);
loadArrayList(getApplicationContext());
adapter = new ListAdapter(this, R.layout.row, data);
listView.setAdapter(adapter);
registerForContextMenu(listView);
save_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View dlgview = View.inflate(MainActivity.this, R.layout.adds, null);
//adds.xml
final EditText et_title = (EditText) dlgview.findViewById(R.id.editText1);
final EditText et_info = (EditText) dlgview.findViewById(R.id.editText2);
ImageView img1 = (ImageView) dlgview.findViewById(R.id.imageView2);
AlertDialog.Builder dlg = new AlertDialog.Builder(MainActivity.this);
dlg.setTitle("ADD");
dlg.setView(dlgview);
dlg.setNegativeButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
try{
jsonObject.put("title", et_title.getText().toString());
jsonObject.put("info", et_info.getText().toString());
jsonObject.put("image",img);
jsonArray.put(jsonObject);
} catch (JSONException e){
e.printStackTrace();
}
jsondata = jsonArray.toString();
saveArrayList();
adapter.notifyDataSetChanged();
}
});
dlg.setPositiveButton("Cancel",null);
dlg.show();
}
});
}//End of onCreate
private void saveArrayList(){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString("jsonData", jsondata);
Log.i("moi","get Data test : " + "jsonData");
editor.apply();
}
private void loadArrayList(Context context){
SharedPreferences sharedPrefs2 = PreferenceManager.getDefaultSharedPreferences(context);
int size = sharedPrefs2.getInt("appreciation_size",0);
String strJson = sharedPrefs2.getString("jsonData", "fail");
Log.i("moi","get SharedPreferences test : " + strJson);
if (strJson != "fail")
{
try {
JSONArray response = new JSONArray(strJson);
for (int i=0; i<size; i++)
{
JSONObject jsonobject = response.getJSONObject(i);
title = jsonobject.getString("title");
Log.i("moi","title test : " + "title");
info = jsonobject.getString("info");
Log.i("moi","info test : " + "info");
data.add(new List(title, info, img));
}
adapter = new ListAdapter(getApplicationContext(), R.layout.row, data);
listView.setAdapter(adapter);
} catch (JSONException e){
e.printStackTrace();
}
}
}
}//End of class
Because you just called loadArrayList() once in onCreate(). That means your data in adapter just changes once.
you call adapter.notifyDataSetChanged() but this method doesnt callloadArrayList()`.
so try to save new json into data in onClick()
Try to remove your code:
adapter = new ListAdapter(this, R.layout.row, data);
listView.setAdapter(adapter);
in CreateView.
I think you set adapter listview double.
i hope that helps you.. thanks
I am developing an app. In it I'm using a listview. When I click on list item, it should go to next activity, i.e ProfileActivity2.java. It works fine, but in this ProfileActivty2 there is a button at the bottom and when I click on this button my app gets crashed and stopped in listview page. And shows the error java.lang.Throwable: setStateLocked in listview layout file i.e At setContentView. How do I solve this error?
//ProfileActivity2.java
public class ProfileActivity2 extends AppCompatActivity {
//Textview to show currently logged in user
private TextView textView;
private boolean loggedIn = false;
Button btn;
EditText edname,edaddress;
TextView tvsname, tvsprice;
NumberPicker numberPicker;
TextView textview1,textview2;
Integer temp;
String pname, paddress, email, sname, sprice;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile1);
//Initializing textview
textView = (TextView) findViewById(R.id.textView);
edname=(EditText)findViewById(R.id.ed_pname);
edaddress=(EditText)findViewById(R.id.ed_add);
tvsname=(TextView)findViewById(R.id.textView_name);
tvsprice=(TextView)findViewById(R.id.textView2_price);
btn=(Button)findViewById(R.id.button);
Intent i = getIntent();
// getting attached intent data
String name = i.getStringExtra("sname");
// displaying selected product name
tvsname.setText(name);
String price = i.getStringExtra("sprice");
// displaying selected product name
tvsprice.setText(price);
numberPicker = (NumberPicker)findViewById(R.id.numberpicker);
numberPicker.setMinValue(0);
numberPicker.setMaxValue(4);
final int foo = Integer.parseInt(price);
textview1 = (TextView)findViewById(R.id.textView1_amount);
textview2 = (TextView)findViewById(R.id.textView_seats);
// numberPicker.setValue(foo);
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
temp = newVal * foo;
// textview1.setText("Selected Amount : " + temp);
// textview2.setText("Selected Seats : " + newVal);
textview1.setText(String.valueOf(temp));
textview2.setText(String.valueOf(newVal));
// textview1.setText(temp);
// textview2.setText(newVal);
}
});
//Fetching email from shared preferences
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// submitForm();
// Intent intent = new Intent(ProfileActivity2.this, SpinnerActivity.class);
// startActivity(intent);
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);
String email = sharedPreferences.getString(Config.EMAIL_SHARED_PREF, "Not Available");
textView.setText(email);
if(loggedIn){
submitForm();
Intent intent = new Intent(ProfileActivity2.this, SpinnerActivity.class);
startActivity(intent);
}
}
});
}
private void submitForm() {
// Submit your form here. your form is valid
//Toast.makeText(this, "Submitting form...", Toast.LENGTH_LONG).show();
String pname = edname.getText().toString();
String paddress = edaddress.getText().toString();
String sname = textview1.getText().toString();
// String sname= String.valueOf(textview1.getText().toString());
String sprice= textview2.getText().toString();
// String sprice= String.valueOf(textview2.getText().toString());
String email= textView.getText().toString();
Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
new SignupActivity(this).execute(pname,paddress,sname,sprice,email);
}
}
//SignupActivity
public class SignupActivity extends AsyncTask<String, Void, String> {
private Context context;
Boolean error, success;
public SignupActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String pname = arg0[0];
String paddress = arg0[1];
String sname = arg0[2];
String sprice = arg0[3];
String email = arg0[4];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?pname=" + URLEncoder.encode(pname, "UTF-8");
data += "&paddress=" + URLEncoder.encode(paddress, "UTF-8");
data += "&sname=" + URLEncoder.encode(sname, "UTF-8");
data += "&sprice=" + URLEncoder.encode(sprice, "UTF-8");
data += "&email=" + URLEncoder.encode(email, "UTF-8");
link = "http://example.in/Spinner/update.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
// return new String("Exception: " + e.getMessage());
// return null;
}
return null;
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
Log.e("TAG", jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Success! Your are Now MangoAir User.", Toast.LENGTH_LONG).show();
} else if (query_result.equals("FAILURE")) {
Toast.makeText(context, "Looks Like you already have Account with US.", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
// Toast.makeText(context, "Error parsing JSON Please data Fill all the records.", Toast.LENGTH_SHORT).show();
// Toast.makeText(context, "Please LogIn", Toast.LENGTH_SHORT).show();
Toast.makeText(context, "Please Login", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context, "Grrr! Check your Internet Connection.", Toast.LENGTH_SHORT).show();
}
}
}
//List_Search
public class List_Search extends AppCompatActivity {
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String SNAME = "sname";
static String SPRICE = "sprice";
Context ctx = this;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.list_search);
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(List_Search.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://example.in/MangoAir_User/mangoair_reg/ListView1.php");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("result");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("sname", jsonobject.getString("sname"));
map.put("sprice", jsonobject.getString("sprice"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listView_search);
// Pass the results into ListViewAdapter.java
// adapter = new ListViewAdapter(List_Search.this, arraylist);
adapter = new ListViewAdapter(ctx, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
//ListViewAdapter
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
private boolean loggedIn = false;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView name,price;
Button btn;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.search_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
name = (TextView) itemView.findViewById(R.id.textView8_sellernm);
// Capture position and set results to the TextViews
name.setText(resultp.get(List_Search.SNAME));
price = (TextView) itemView.findViewById(R.id.textView19_bprice);
// Capture position and set results to the TextViews
price.setText(resultp.get(List_Search.SPRICE));
btn=(Button)itemView.findViewById(R.id.button3_book);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resultp = data.get(position);
Intent intent = new Intent(context, ProfileActivity2.class);
// Pass all data rank
intent.putExtra("sname", resultp.get(List_Search.SNAME));
intent.putExtra("sprice", resultp.get(List_Search.SPRICE));
context.startActivity(intent);
}
});
return itemView;
}
}
context.startActivity(intent);
I think the error is at this line inside btn.setOnClickListener of getview block just use startActivity(intent);
I am working on android app and put filtration functionality on Listview. But I got below error:
java.lang.RuntimeException: Unable to start activity
componentInfo:java.lang.NullPointerException: Attempt to invoke
virtual method void
android.widget.EditText.addTextchangedListener(android.text.TextWatcher)
on a Null object Reference
Below is my code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shopdetail);
aq=new AQuery(this);
value=5;
GPSTracker gps = new GPSTracker(Shopdetail.this);
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
getdatalatlog(latitude,longitude);
}else{
gps.showSettingsAlert();
}
Intent openStartingPoint=getIntent();
String city=openStartingPoint.getStringExtra("spinnerText");
bindcity(city);
final EditText inputSearch = (EditText)findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
//Shopdetail.this.adapter.getFilter().filter(cs);
//((SimpleAdapter)Shopdetail.this.adapter).getFilter().filter(cs);
// ((SimpleAdapter)getListAdapter()).getFilter().filter(cs);
//get the text in the EditText
EditText inputSearch = (EditText)findViewById(R.id.inputSearch);
String searchString=inputSearch.getText().toString();
int textLength=searchString.length();
searchResults.clear();
for(int i=0;i<mCommentList.size();i++)
{
String shopName=mCommentList.get(i).get(TAG_TITLE).toString();
if(textLength<=shopName.length()){
//compare the String in EditText with Names in the ArrayList
if(searchString.trim().equalsIgnoreCase(shopName.trim().substring(0,textLength))){
searchResults.add(mCommentList.get(i));
getdata();}
}
}
adapter.notifyDataSetChanged();
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
private void getdata() {
// TODO Auto-generated method stub
String[] data = new String[]{TAG_TITLE,TAG_USERNAME ,TAG_CONTACT ,TAG_MESSAGE ,TAG_LATITUDE , TAG_LONGITUDE };
int[] to= new int[] {R.id.shop_name,R.id.address,R.id.contact,R.id.distance,R.id.latitude,R.id.longitude};
final SimpleAdapter adapter = new SimpleAdapter(this, mCommentList,R.layout.single_post, data,to);
ListView lv = ( ListView ) findViewById(android.R.id.list);
lv.setAdapter(adapter);
}
Below is my code to firstly bind data.
private void getdatalatlog(double latitude, double longitude) {
// TODO Auto-generated method stub
//value=5;
String url = "http://192.168.2.4/PHP/webservice/comments.php?latitude='"+latitude+"'&longitude='"+longitude+"'&value='"+value+"'";
aq.progress(R.id.progressBar1).ajax(url, JSONObject.class, this,"jsonCallback");
}
#SuppressWarnings("unchecked")
public void jsonCallback(String url, JSONObject json, AjaxStatus status) {
if (json != null) {
List<String> city = new ArrayList<String>();
mCommentList = new ArrayList<HashMap<String, Object>>();
Gson gson = new GsonBuilder().create();
try {
JSONArray jsonResponse = json.getJSONArray("posts");
city = gson.fromJson(jsonResponse.toString(),List.class);
for (int i = 0; i < jsonResponse.length(); i++) {
JSONObject c = jsonResponse.getJSONObject(i);
String title = c.getString(TAG_TITLE);
String content = c.getString(TAG_MESSAGE);
String username = c.getString(TAG_USERNAME);
String lat = c.getString(TAG_LATITUDE);
String log = c.getString(TAG_LONGITUDE);
String cont = c.getString(TAG_CONTACT);
// creating new HashMap
HashMap<String, Object> map = new HashMap<String, Object>();
map.put(TAG_TITLE, title);
map.put(TAG_MESSAGE, content);
map.put(TAG_USERNAME, username);
map.put(TAG_LATITUDE, lat);
map.put(TAG_LONGITUDE, log);
map.put(TAG_CONTACT, cont);
// adding HashList to ArrayList
mCommentList.add(map);
searchResults=new ArrayList<HashMap<String,Object>>(mCommentList);
//HashMap<String, String> map1 = new HashMap<String, String>();
//map1.put(TAG_TITLE, title);
//sortdata;
}
}
catch (JSONException e) {
Toast.makeText(aq.getContext(), "Error in parsing JSON", Toast.LENGTH_LONG).show();
}
catch (Exception e) {
Toast.makeText(aq.getContext(), "Something went wrong", Toast.LENGTH_LONG).show();
}
String[] data = new String[]{TAG_TITLE,TAG_USERNAME ,TAG_CONTACT ,TAG_MESSAGE ,TAG_LATITUDE , TAG_LONGITUDE };
int[] to= new int[] {R.id.shop_name,R.id.address,R.id.contact,R.id.distance,R.id.latitude,R.id.longitude};
final SimpleAdapter adapter = new SimpleAdapter(this, mCommentList,R.layout.single_post, data,to);
ListView lv = ( ListView ) findViewById(android.R.id.list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent();
Bundle b = new Bundle();
String name= ((TextView) view.findViewById(R.id.shop_name)).getText().toString()+" , "+((TextView) view.findViewById(R.id.contact)).getText().toString();
String lati= ((TextView) view.findViewById(R.id.latitude)).getText().toString();
String longi= ((TextView) view.findViewById(R.id.longitude)).getText().toString();
b.putString("shop",name);
b.putString("lati",lati);
b.putString("long",longi);
intent.setClass(Shopdetail.this, Mapview.class);
intent.putExtras(b);
startActivity(intent);
}
});
}
}
When user type letter on EditText the data is filtered and its bind in listview according to that. Its not working. Please guide me.
Thanks so much in advance.
You forget to initialized inputSearch
inputSearch=(EditText)findViewById(R.id.editTextId);
OR move
EditText inputSearch = (EditText)findViewById(R.id.inputSearch);
before
inputSearch.addTextChangedListener(new TextWatcher() {
Invoking method on Null object reference will always throw java.lang.NullPointerException.
In your case, logs clearly indicate "Attempt to invoke method addTextchangedListener(android.text.TextWatcher) on a Null object Reference".
In short - inputSearch is null and should be initialized before any method invocations.
In my program i am showing multilevel Listview, but whenever i am calling another Activity then Fragment Tabs are not appearing.
I am using this great tutorial: http://www.androidbegin.com/tutorial/android-actionbarsherlock-viewpager-tabs-tutorial/
See below Images, 1st Level ListView:
2nd Level ListView:
ListCategoryFragment.xml:-
public class ListCategoryFragment extends SherlockFragment implements OnItemClickListener {
ListView lview3;
ListCategoryAdapter adapter;
private ArrayList<Object> itemList;
private ItemBean bean;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Get the view from fragmenttab1.xml
View view = inflater.inflate(R.layout.fragment_category_tab, container, false);
prepareArrayList();
lview3 = (ListView) view.findViewById(R.id.listView1);
adapter = new ListCategoryAdapter(getActivity(), itemList);
lview3.setAdapter(adapter);
lview3.setOnItemClickListener(this);
return view;
}
private static final int categoryFirst = 0;
private static final int categorySecond = 1;
private static final int categoryThird = 2;
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
// Set up different intents based on the item clicked:
switch (position)
{
case categoryFirst:
Intent intent1 = new Intent(getActivity(), ListItemActivity.class);
intent1.putExtra("category", "Category - 1");
startActivity(intent1);
break;
case categorySecond:
Intent intent2 = new Intent(getActivity(), ListItemActivity.class);
intent2.putExtra("category", "Category - 2");
startActivity(intent2);
break;
case categoryThird:
Intent intent3 = new Intent(getActivity(), ListItemActivity.class);
intent3.putExtra("category", "Category - 3");
startActivity(intent3);
break;
default:
break;
}
}
public void prepareArrayList()
{
itemList = new ArrayList<Object>();
AddObjectToList("Category - 1");
AddObjectToList("Category - 2");
AddObjectToList("Category - 3");
}
// Add one item into the Array List
public void AddObjectToList(String title)
{
bean = new ItemBean();
bean.setTitle(title);
itemList.add(bean);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
setUserVisibleHint(true);
}
}
ListItemActivity.java:-
public class ListItemActivity extends SherlockFragmentActivity {
static String URL = "http://www.site.url/tone.json";
static String KEY_CATEGORY = "item";
static final String KEY_TITLE = "title";
ListView list;
ListItemAdapter adapter;
/** Called when the activity is first created. */
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_item_list);
final ArrayList<HashMap<String, String>> itemsList = new ArrayList<HashMap<String, String>>();
list = (ListView) findViewById(R.id.listView1);
adapter = new ListItemAdapter(this, itemsList);
list.setAdapter(adapter);
Bundle bdl = getIntent().getExtras();
KEY_CATEGORY = bdl.getString("category");
if (isNetworkAvailable()) {
new MyAsyncTask().execute();
} else {
AlertDialog alertDialog = new AlertDialog.Builder(ListItemActivity.this).create();
alertDialog.setMessage("The Internet connection appears to be offline.");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
private Intent getDefaultShareIntent(){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "SUBJECT");
intent.putExtra(Intent.EXTRA_TEXT, "TEXT");
startActivity(Intent.createChooser(intent, "Share via"));
return intent;
}
/** The event listener for the Up navigation selection */
#Override
public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
switch(item.getItemId())
{
case android.R.id.home:
finish();
break;
case R.id.menu_item_share:
getDefaultShareIntent();
break;
}
return true;
}
private boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
return (info != null);
}
class MyAsyncTask extends
AsyncTask<String, Integer, ArrayList<HashMap<String, String>>> {
private ProgressDialog progressDialog = new ProgressDialog(
ListItemActivity.this);
#Override
protected void onPreExecute() {
progressDialog.setMessage("Loading, Please wait.....");
progressDialog.show();
}
final ArrayList<HashMap<String, String>> itemsList = new ArrayList<HashMap<String, String>>();
#Override
protected ArrayList<HashMap<String, String>> doInBackground(
String... params) {
HttpClient client = new DefaultHttpClient();
// Perform a GET request for a JSON list
HttpUriRequest request = new HttpGet(URL);
// Get the response that sends back
HttpResponse response = null;
try {
response = client.execute(request);
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Convert this response into a readable string
String jsonString = null;
try {
jsonString = StreamUtils.convertToString(response.getEntity()
.getContent());
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Create a JSON object that we can use from the String
JSONObject json = null;
try {
json = new JSONObject(jsonString);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
JSONArray jsonArray = json.getJSONArray(KEY_CATEGORY);
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonObject = jsonArray.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put(KEY_TITLE, jsonObject.getString(KEY_TITLE));
itemsList.add(map);
}
return itemsList;
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return null;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
list = (ListView) findViewById(R.id.listView1);
adapter = new ListItemAdapter(ListItemActivity.this, itemsList);
list.setAdapter(adapter);
TextView lblTitle = (TextView) findViewById(R.id.text);
lblTitle.setText(KEY_CATEGORY);
this.progressDialog.dismiss();
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> map = itemsList.get(position);
Intent in = new Intent(ListItemActivity.this, ListItemDetailActivity.class);
in.putExtra(KEY_TITLE, map.get(KEY_TITLE));
startActivity(in);
}
});
}
}
}
This is the normal behavior because you are moving from the Fragment Activity to a normal Activity. But only your first activity has the tabs.
The correct way of doing this is to remove the intents and the new activities. Instead it should be replaced with fragments itself.
For example, in the list item click, stop calling the Intent to the new fragment activity, and replace it calling a fragment itself.
There will be only one Activity and that will be the one which is holding the tabs and all others should be fragments. You just need to replace the fragments from within the same activity.