I have developed a layout which has 2 textboxes and 1 button. At the first, the button is appear and two textboxes are disappeared. However, I dont know how can I change the visibility of textboxes and other components to appear when the insert button is pressed. Please explain simply because I am new in android.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:orientation="vertical"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".Main3Activity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:id="#+id/textView"
android:visibility="gone" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editTextName"
android:visibility="gone" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address"
android:id="#+id/textView2"
android:visibility="gone" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editTextAddress"
android:visibility="gone" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Insert"
android:onClick="insert"
android:id="#+id/button" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textViewResult" />
</LinearLayout>
Main2Activity
package com.example.alan.mainactivity;
import org.apache.http.util.EntityUtils;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.view.View;
import android.widget.Toast;
import android.view.View.OnClickListener;
public class Main2Activity extends ActionBarActivity {
public static final String USER_NAME1 = "USERNAME";
String myJSON;
private EditText editTextName;
private EditText editTextAdd;
private static final String TAG_RESULTS="result";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_ADD ="address";
JSONArray peoples = null;
ArrayList<HashMap<String, String>> personList;
ListView list;
Button btn_insert=(Button)findViewById(R.id.button);
btn_insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView textView= (TextView)findViewById(R.id.textView);
textView.setVisibility(View.VISIBLE);
//Similarly the other views.....
}
});
public void insert(View view){
String name = editTextName.getText().toString();
String add = editTextAdd.getText().toString();
insertToDatabase(name, add);
}
private void insertToDatabase(String name, String add){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String paramAddress = params[1];
String name = editTextName.getText().toString();
String add = editTextAdd.getText().toString();
Intent intent = getIntent();
String username = intent.getStringExtra(MainActivity.USER_NAME).toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("address", add));
nameValuePairs.add(new BasicNameValuePair("user", username));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(
"http://www.oobac.com/app/insert-db.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "success";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
TextView textViewResult = (TextView) findViewById(R.id.textViewResult);
textViewResult.setText("Inserted");
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name, add);
}
//-----------------------
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
Intent intent = getIntent();
String username = intent.getStringExtra(MainActivity.USER_NAME);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextAdd = (EditText) findViewById(R.id.editTextAddress);
TextView textView = (TextView) findViewById(R.id.textView3);
textView.setText("Welcome " + username);
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
getData();
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
peoples = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<peoples.length();i++){
JSONObject c = peoples.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String address = c.getString(TAG_ADD);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_ID,id);
persons.put(TAG_NAME,name);
persons.put(TAG_ADD,address);
personList.add(persons);
}
ListAdapter adapter = new SimpleAdapter(
Main2Activity.this, personList, R.layout.list_item,
new String[]{TAG_ID,TAG_NAME,TAG_ADD},
new int[]{R.id.id, R.id.name, R.id.address}
);
list.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
//--------------------------------------------
Intent intent = getIntent();
String username = intent.getStringExtra(MainActivity.USER_NAME);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", username));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.oobac.com/app/amir.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpclient.execute(httppost);
String st = EntityUtils.toString(response.getEntity());
Log.d("TK SUPPORT", "In the try Loop" + st);
myJSON = st;
} catch (Exception e) {
Log.d("TK SUPPORT", "Connection Error : " + e.toString());
}
return "OK";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
SAMPLE SNIPPET
replace your onCreate method to this method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
Intent intent = getIntent();
String username = intent.getStringExtra(MainActivity.USER_NAME);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextAdd = (EditText) findViewById(R.id.editTextAddress);
TextView textView = (TextView) findViewById(R.id.textView3);
Button btn_insert=(Button)findViewById(R.id.button);
btn_insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView textView= (TextView)findViewById(R.id.textView);
textView.setVisibility(View.VISIBLE);
//Similarly the other views.....
}
});
textView.setText("Welcome " + username);
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
getData();
}
Try this:
EditText name = (EditText)findViewById(R.id.editTextName);
name.setVisibility(View.GONE);
Declare a class variable like this
private TextView yourTextView;
You should get the instance of your TextView like this
yourTextView = (TextView)findViewById(R.id.your_editText);
Then on button click, setVisibility to visible
Button mButton = (Button)findViewById(R.id.m_button);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yourTextView.setVisibility(View.VISIBLE);
}
});
To hide, setVisibility to Gone
yourTextView.setVisibility(View.GONE);
Use the setVisibility property to hide your views.
yourView.setVisibility(View.GONE);
View.GONE This view is invisible, and it doesn't take any space for layout purposes.
Also
yourView.setVisibility(View.INVISIBLE);
View.INVISIBLE This view is invisible, but it still takes up space for layout purposes.
Button btn_insert=(Button)findViewById(R.id.button);
btn_insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView textView= (TextView)findViewById(R.id.textView);
textView.setVisibility(View.VISIBLE);
//Similarly the other views.....
}
});
Firstly, You are setting android:onClick="insert" in layout xml and you are also setting click listener in onCreate method too. So either remove from xml or onCreate listener. Secondly, in onClick, TextView textView=
(TextView)findViewById(R.id.textView);
textView.setVisibility(View.VISIBLE);
Hope this helps.
In Simple way Just put your onClicklistener() of button inside onCreate() method like this ..
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
Intent intent = getIntent();
String username = intent.getStringExtra(MainActivity.USER_NAME);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextAdd = (EditText) findViewById(R.id.editTextAddress);
TextView textView = (TextView) findViewById(R.id.textView3);
Button btn_insert=(Button)findViewById(R.id.button);
btn_insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView textView= (TextView)findViewById(R.id.textView);
textView.setVisibility(View.VISIBLE);
//do it here whatever u want to do on press of button
//Similarly the other views.....
}
});
textView.setText("Welcome " + username);
list = (ListView) findViewById(R.id.listView);
personList = new ArrayList<HashMap<String,String>>();
getData();
}
Related
I currently working with a project and stuck on the radio button which getting only the checked radio in xml, I search many case regarding with this concern and still got the same problem.
here is the activity which toasting only the checked radio in xml
package com.example.kapoyei.hatidtubiganapp;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.example.kapoyei.hatidtubiganapp.helper.Http;
import com.example.kapoyei.hatidtubiganapp.helper.Network;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
public class ClientActivity extends Activity implements View.OnClickListener {
public static String jsonObject;
SharedPreferences sharedPref;
Intent i;
Button btnLogout, btnBreakPoint;
Spinner spnStation;
ImageView btnReserve, btnStationList, btnPending, btnHistory;
TextView txtSelectDate;
EditText no_container;
RadioGroup radioGroup;
RadioButton radioButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnReserve = (ImageView) findViewById(R.id.btnReserve);
btnStationList = (ImageView) findViewById(R.id.btnStation);
btnPending = (ImageView) findViewById(R.id.btnPending);
btnHistory = (ImageView) findViewById(R.id.btnHistory);
btnPending.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
i = new Intent(ClientActivity.this, PendingClientOrderActivity.class);
startActivity(i);
}
});
btnStationList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
i = new Intent(ClientActivity.this, StationList.class);
startActivity(i);
}
});
btnReserve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(ClientActivity.this);
LayoutInflater inflater = getLayoutInflater();
view = inflater.inflate(R.layout.layout_dialog_reserve, null);
spnStation = (Spinner) view.findViewById(R.id.spnStation);
txtSelectDate = (TextView) view.findViewById(R.id.txtDate);
no_container = (EditText) view.findViewById(R.id.etContainer);
radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
radioButton = (RadioButton) view.findViewById(radioGroup.getCheckedRadioButtonId());
btnBreakPoint = (Button) view.findViewById(R.id.btnBreakPoint);
final Calendar c = Calendar.getInstance();
final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, day);
String dateFormat = "MM/dd/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat, Locale.US);
txtSelectDate.setText(sdf.format(c.getTime()));
}
};
txtSelectDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new DatePickerDialog(ClientActivity.this,
date,
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH)).show();
}
});
btnBreakPoint.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(no_container.getText().toString().isEmpty() || txtSelectDate.getText().toString().equalsIgnoreCase("-- CLICK TO DATE DELIVER --")) {
Toast.makeText(getApplicationContext(), "All fields require", Toast.LENGTH_SHORT).show();
} else {
/*Bundle bundle = new Bundle();
bundle.putString("station", spnStation.getSelectedItem().toString());
bundle.putString("date", txtSelectDate.getText().toString());
bundle.putString("no_container", no_container.getText().toString());
bundle.putString("type", Integer.toString(radioGroup.getCheckedRadioButtonId()));
i = new Intent(ClientActivity.this, CheckOut.class);
i.putExtras(bundle);
startActivity(i);*/
String typeOrder = radioButton.getText().toString();
Toast.makeText(getApplicationContext(), typeOrder, Toast.LENGTH_LONG).show();
}
}
});
Network network = new Network(getApplicationContext());
if(network.isNetwork()) {
new ClientActivity.GetStationList().execute();
} else {
Toast.makeText(getApplicationContext(), "Coud not get stations", Toast.LENGTH_SHORT).show();
}
builder.setView(view);
builder.setCancelable(true);
AlertDialog dialog = builder.create();
dialog.show();
}
});
btnHistory.setOnClickListener(this);
btnLogout.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if(view.getId() == R.id.btnLogout) {
finish();
sharedPref = getSharedPreferences("ht", MODE_PRIVATE);
SharedPreferences.Editor modify = sharedPref.edit();
modify.putBoolean("login", false);
modify.putString("id", "");
modify.putString("auth", "");
modify.apply();
i = new Intent(ClientActivity.this, LoginActivity.class);
startActivity(i);
}
if(view.getId() == R.id.btnHistory) {
i = new Intent(ClientActivity.this, HistoryActivity.class);
startActivity(i);
}
}
public class GetStationList extends AsyncTask<Void, Void, String> {
ProgressDialog pd;
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(ClientActivity.this);
pd.setMessage("Getting station ...");
pd.setCancelable(false);
pd.show();
}
#Override
protected void onPostExecute(String result) {
pd.cancel();
json(result);
}
#Override
protected String doInBackground(Void... voids) {
String data = "";
jsonObject = "";
try {
String link = (String) Http.url + "?type=getstationlist";
URL getURL = new URL(link);
HttpURLConnection httpURLConnection = (HttpURLConnection) getURL.openConnection();
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setDoInput(true);
httpURLConnection.connect();
InputStream is = (InputStream) httpURLConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
while((data = reader.readLine()) != null) {
jsonObject += data;
}
Log.i("", jsonObject);
return jsonObject;
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
public void json(String json) {
List<String> collectionName = new ArrayList<>();
if(json != null) {
try {
JSONObject jobj = new JSONObject(json);
JSONArray jarray = jobj.getJSONArray("stationlist");
String name = "";
String id = "";
for(int i = 0; i < jarray.length(); i++) {
JSONObject obj = jarray.getJSONObject(i);
name = obj.getString("name");
collectionName.add(name);
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(getBaseContext(), android.R.layout.simple_list_item_1, collectionName);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnStation.setAdapter(adapter);
} catch(Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Connection problem", Toast.LENGTH_SHORT).show();
}
}
}
}
and here is the xml where located the layout of my radio
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="20dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Select Station"
android:layout_margin="10dp"
android:textSize="20sp"/>
<Spinner
android:id="#+id/spnStation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Date"
android:layout_margin="10dp"
android:textSize="20sp"/>
<TextView
android:id="#+id/txtDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="-- CLICK TO DATE DELIVER --"
android:textSize="15sp"
android:layout_margin="10dp"
android:layout_gravity="center"
android:textAlignment="center"/>
<EditText
android:id="#+id/etContainer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="No. Of Containers"
android:layout_margin="10dp"/>
<RadioGroup
android:id="#+id/radioGroup"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RadioButton
android:id="#+id/Gallon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Gallon"
android:checked="true"/>
<RadioButton
android:id="#+id/Litre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Litre" />
</RadioGroup>
<Button
android:id="#+id/btnBreakPoint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_margin="10dp"
android:text="Proceed to Check Out" />
</LinearLayout>
</RelativeLayout>
You can apply the below codes:
int radioid = radioButtonGroup.getCheckedRadioButtonId();
View radio_button= radioButtonGroup.findViewById(radioButtonID);
int index = radioButtonGroup.indexOfChild(radioButton);
If the RadioGroup contains other Views (like a TextView) then the indexOfChild() method will return wrong index.
To get selected RadioButton Text on RadioGroup follow the below code:
RadioButton radio = (RadioButton) radioButtonGroup.getChildAt(index);
String text = radio.getText().toString();
Why this is happened? Because before you click Break Point button, you change the radio button id but not bind it to your variable, your variable still storing the old value. You need to add this code
radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
radioButton = (RadioButton) view.findViewById(radioGroup.getCheckedRadioButtonId());
above
String typeOrder = radioButton.getText().toString();
so it will shown
btnBreakPoint.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
...
radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
radioButton = (RadioButton) view.findViewById(radioGroup.getCheckedRadioButtonId());
String typeOrder = radioButton.getText().toString();
...
}
or you can move the scope of radioGroup assignment to onCreate scope
I have 2 radiobuttons and 1 button. I want that when i click the normal button it checks which radio button is checked and executes a method based on that. The following is the code i have used but the app crashes when i click the button
#Override
public void onClick(View v) {
radioGroup = (RadioGroup) v.findViewById(R.id.radioPost);
rdpublic=(RadioButton) v.findViewById(R.id.radioPublic);
rdprivate=(RadioButton) v.findViewById(R.id.radioPrivate);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId)
{
if(rdpublic.isChecked())
{
new PostPublic().execute();
}
else if(rdprivate.isChecked())
{
new PostPrivate().execute;
}
}
});
}
Try this.....
normalBtn= (Button) findViewById(R.id.Btn);
rdpublic=(RadioButton) findViewById(R.id.radioPublic);
rdprivate=(RadioButton) findViewById(R.id.radioPrivate);
normalBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
try {
if(rdpublic.isChecked())
{
new PostPublic().execute();
}
else if(rdprivate.isChecked())
{
new PostPrivate().execute;
}
}catch(Exception e)
{
e.printStackTrace();
}
}
});
Why are you using the button view to find the RadioButtons and Group? Instead of v.findViewById, you should just use findViewById.
your code assumes that your Buttons or RadioButtons are child Views of the passed View v. Which is actually wrong and that is why you are getting an NPE.
This is the full code.
package com.project.bsc.radianstores;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.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.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class PostEnquiry extends Fragment implements OnClickListener {
public String[] sItemType;
public int position =0;
private EditText Message;
JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
private static final String POST_PRIVATE_URL = "http://192.168.1.102/webservice/privateenquiry.php";
private static final String POST_PUBLIC_URL = "http://192.168.1.102/webservice/publicenquiry.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private Button BtnSave;
private RadioGroup radioGroup;
private RadioButton rdpublic;
private RadioButton rdprivate;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.enquiry, container, false);
BtnSave = (Button) v.findViewById(R.id.sendEnquiry);
Message = (EditText)v.findViewById(R.id.MessageBox);
Spinner spItemType = (Spinner) v.findViewById(R.id.spinnerItemType);
sItemType = getResources().getStringArray(R.array.ItemType);
BtnSave.setOnClickListener(this);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item, sItemType);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spItemType.setAdapter(dataAdapter);
//setting up listener for the spinner
spItemType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
int index = arg0.getSelectedItemPosition();
position = index;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
return v;
}
#Override
public void onClick(View v) {
radioGroup = (RadioGroup) v.findViewById(R.id.radioPost);
rdpublic=(RadioButton) v.findViewById(R.id.radioPublic);
rdprivate=(RadioButton) v.findViewById(R.id.radioPrivate);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
if(checkedId == rdpublic.getId()) {
new PostPublic().execute();
}
else if (checkedId == rdprivate.getId()) {
//new PostPrivate().execute();
}
}
});
}
class PostPublic extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Posting Enquiry...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String strItemType = sItemType[position];;
String strMessage = Message.getText().toString();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
String strUsername = sp.getString("Username", "");
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Username", strUsername));
params.add(new BasicNameValuePair("Item_Type", strItemType));
params.add(new BasicNameValuePair("Message", strMessage));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
POST_PUBLIC_URL, "POST", params);
// full json response
Log.d("Enquiry Posting attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Enquiry Posted Successful!", json.toString());
return json.getString(TAG_MESSAGE);
}else{
Log.d("Posting Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null)
Toast.makeText(getActivity(), file_url, Toast.LENGTH_LONG).show();
}
}
}
I am new to Android. I can't get my ListView to populate. I am aware that this question has been asked on SO multiple times before and I have tried the things suggested in other questions (e.g. making sure my orientation is set to vertical, calling notifyDataSetChanged etc) and it still won't work. My activity class is as follows:
package com.michaelnares.twitterclient;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;
import twitter4j.*;
import twitter4j.conf.ConfigurationBuilder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Created by michael on 01/05/2014.
*/
public class SearchActivity extends Activity {
EditText queryEditText = null;
String queryText = null;
private Context context = this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
queryEditText = (EditText) findViewById(R.id.queryEditText);
queryText = (queryEditText.getText().toString());
final Context context = this;
Button queryButton = (Button) findViewById(R.id.queryButton);
queryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (queryText.equals(null)) {
Toast.makeText(context, "You did not enter a query", Toast.LENGTH_SHORT).show();
} else {
new SearchAsyncTask().execute();
}
}
});
} // ends onCreate()
private class SearchAsyncTask extends AsyncTask<String, String, ArrayList<String>>
{
private ProgressDialog dialog = new ProgressDialog(SearchActivity.this);
private ArrayList<String> searchResults;
#Override
protected void onPreExecute()
{
super.onPreExecute();
dialog.setMessage("Getting data...");
dialog.setIndeterminate(false);
dialog.setCancelable(true);
dialog.show();
}
#Override
protected ArrayList<String> doInBackground(String... strings) {
APIClient client = new APIClient();
searchResults = client.getQueryResults(queryText);
return searchResults;
}
#Override
protected void onPostExecute(ArrayList<String> results)
{
dialog.dismiss();
results.addAll(searchResults);
final ListView searchListView = (ListView) findViewById(R.id.searchListView);
final ArrayAdapter adapter = new ArrayAdapter(context, android.R.layout.simple_list_item_1, results);
adapter.notifyDataSetChanged();
searchListView.setAdapter(adapter);
}
}
} //ends class
and my XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp" >
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/search"
android:textSize="25dp"/>
<EditText android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/queryEditText"
android:ems="20"/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/query"
android:id="#+id/queryButton"
android:textSize="15dp"/>
<ListView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/searchListView">
</ListView>
</LinearLayout>
Here is my API client class also:
package com.michaelnares.twitterclient;
import android.util.Log;
import twitter4j.*;
import twitter4j.conf.ConfigurationBuilder;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Created by michael on 01/05/2014.
*/
public class APIClient
{
ArrayList<String> statusArrayList = new ArrayList<String>();
ArrayList<String> searchArrayList = new ArrayList<String>();
public ArrayList<String> getHomeTimeline() {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(AuthConstants.API_KEY)
.setOAuthConsumerSecret(AuthConstants.API_SECRET)
.setOAuthAccessToken(AuthConstants.ACCESS_TOKEN)
.setOAuthAccessTokenSecret(AuthConstants.ACCESS_TOKEN_SECRET);
try {
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
List<Status> statuses = twitter.getHomeTimeline();
statusArrayList.clear();
for (Status status : statuses)
{
statusArrayList.add(status.toString());
}
}
catch (TwitterException e)
{
Log.e(LogConstants.LOG, "Failed to get home timeline tweets: " + e.getErrorMessage());
}
return statusArrayList;
} // ends getHomeTimeline() method
public ArrayList<String> getQueryResults(String userQuery)
{
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(AuthConstants.API_KEY)
.setOAuthConsumerSecret(AuthConstants.API_SECRET)
.setOAuthAccessToken(AuthConstants.ACCESS_TOKEN)
.setOAuthAccessTokenSecret(AuthConstants.ACCESS_TOKEN_SECRET);
TwitterFactory tf = new TwitterFactory(cb.build());
Twitter twitter = tf.getInstance();
searchArrayList.clear();
try {
Query query = new Query(userQuery);
QueryResult result;
result = twitter.search(query);
List<Status> tweets = result.getTweets();
int count = 0;
searchArrayList.clear();
for (Iterator<Status> i = tweets.iterator(); i.hasNext();)
{
Status tweet = i.next();
count++;
if (count == 10)
{
break;
}
searchArrayList.add("#" + tweet.getUser().getScreenName() + " - " + tweet.getText());
} // ends for loop
} // ends try block
catch (TwitterException e)
{
Log.e(LogConstants.LOG, "Failed to search tweets: " + e.getErrorMessage());
}
return searchArrayList;
} // ends getQueryResults() method
} // ends class
I'm really struggling to work out what the issue is.
I have made an activity in that one ListView is ther,In that ListView each listItem is having an editText named "qty",which can be edited,one textView is there which displays "price",I need is when i edit the edittext and if the entered value is more than some limi the textView value will change,After that i have to pass them as a parameter to an api as below:
http://yehki.epagestore.in/app_api/updateCart.php?customer_id=41&product_id=30&quantity=90&product_id=23&quantity=90
from that i will get subtotal's of eact item and have to set them to each item in the list,can anyone please help me for it?My code is as below..Please help me save my life...thank you
main.java
package com.epe.yehki.ui;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.epe.yehki.adapter.CartAdapter;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Pref;
import com.example.yehki.R;
public class CartListActivity extends Activity {
private ProgressDialog pDialog;
Intent in = null;
ListView lv;
JSONObject jsonObj;
ArrayList<HashMap<String, String>> cartList;
Bitmap bitmap;;
private CartAdapter cartContent;
JSONArray carts = null;
ImageView back;
TextView tv_place_order, tv_home;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_cart_list);
lv = (ListView) findViewById(R.id.cart_list);
back = (ImageView) findViewById(R.id.iv_bak);
tv_place_order = (TextView) findViewById(R.id.tv_place_order);
tv_home = (TextView) findViewById(R.id.tv_home);
cartList = new ArrayList<HashMap<String, String>>();
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
// execute the cartList api()...........!!!!
new GetCartList().execute();
// listView ClickEvent
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
lv.removeViewAt(position);
cartContent.notifyDataSetChanged();
}
});
tv_home.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
in = new Intent(CartListActivity.this, HomeActivity.class);
startActivity(in);
}
});
tv_place_order.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
/*
* CART LIST PRODUCT LIST...............!!!!!!!!!
*/
private class GetCartList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(CartListActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
String cartUrl = Const.API_CART_LIST + "?customer_id=" + Pref.getValue(CartListActivity.this, Const.PREF_CUSTOMER_ID, "");
BackendAPIService sh = new BackendAPIService();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(cartUrl, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
if (jsonObj.has(Const.TAG_PRO_LIST)) {
carts = jsonObj.getJSONArray(Const.TAG_PRO_LIST);
if (carts != null && carts.length() != 0) {
// looping through All Contacts
for (int i = 0; i < carts.length(); i++) {
JSONObject c = carts.getJSONObject(i);
String proId = c.getString(Const.TAG_PRODUCT_ID);
String proName = c.getString(Const.TAG_PRODUCT_NAME);
String wPrice = c.getString(Const.TAG_WHOLESALE_PRICE);
String rPrice = c.getString(Const.TAG_RETAIL_PRICE);
String qty = c.getString(Const.TAG_QUANTITY);
String proimg = Const.API_HOST + "/" + c.getString(Const.TAG_PRODUCT_IMG);
HashMap<String, String> cartProduct = new HashMap<String, String>();
cartProduct.put(Const.TAG_PRODUCT_ID, proId);
cartProduct.put(Const.TAG_PRODUCT_NAME, proName);
cartProduct.put(Const.TAG_PRODUCT_IMG, proimg);
cartProduct.put(Const.TAG_WHOLESALE_PRICE, wPrice);
cartProduct.put(Const.TAG_RETAIL_PRICE, rPrice);
cartProduct.put(Const.TAG_QUANTITY, qty);
cartList.add(cartProduct);
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
*
* */
cartContent = new CartAdapter(CartListActivity.this, cartList);
lv.setAdapter(cartContent);
}
}
}
In ListAdapter, getItem() should return an item using which you populate the Views
#Override
public HashMap<String, String> getItem(int paramInt) {
return cartArray.get(paramInt);
}
To get all values,
final CartAdapter adapter = (CardAdapter) lv.getAdapter();
for (int i = 0; i < adapter.getCount(); i++) {
final HashMap<String, String> item = adapter.getItem(i);
final String quantity = item.get(Const.TAG_QUANTITY); // value of EditText of one row
}
I am trying to call another class from a class using intent but when i click the button it is made to force close the application and when i tried to debug it,it shows an error source not found.
code is :
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),RegistrationActivity.class);
startActivity(i);
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),SearchDirectly1Activity.class);
startActivity(i);
}
});
main activity xml code is::
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/t1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="#string/Donate" />
<ImageView
android:id="#+id/i1"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_marginTop="20dp"
android:layout_below="#id/t1"
android:src="#drawable/ic_launcher"
/>
<Button
android:id="#+id/b2"
android:layout_width="150dp"
android:layout_height="50dp"
android:layout_alignRight="#+id/t1"
android:layout_below="#+id/i1"
android:layout_marginTop="41dp"
android:text="#string/searching" />
<Button
android:id="#+id/b1"
android:layout_width="150dp"
android:layout_height="50dp"
android:layout_alignBaseline="#+id/b2"
android:layout_alignBottom="#+id/b2"
android:layout_toLeftOf="#+id/b2"
android:text="#string/register" />
</RelativeLayout>
and main activity class is::
package donor.android.blooddonor;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
Button b1;
Button b2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//buttons
b1=(Button) findViewById (R.id.b1);
b2=(Button) findViewById (R.id.b2);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),RegistrationActivity.class);
startActivity(i);
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),SearchDirectly1Activity.class);
startActivity(i);
}
});
}
}
registrationactivity xml is::
package donor.android.blooddonor;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class RegistrationActivity extends Activity{
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText et1;
EditText et2;
EditText et3;
EditText et4;
EditText et5;
EditText et6;
private static String url_create_donor = "http://127.0.0.1/android_connect/create_donor.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.registration);
// Edit Text
et1 = (EditText) findViewById (R.id.et1);
et2 = (EditText) findViewById (R.id.et2);
et3 = (EditText) findViewById (R.id.et3);
et4 = (EditText) findViewById (R.id.et4);
et5 = (EditText) findViewById (R.id.et5);
et6 = (EditText) findViewById (R.id.et6);
// Create button
Button b2 = (Button) findViewById (R.id.b2);
// button click event
b2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view) {
// creating new donor in background thread
new CreateDonor1().execute();
}
});
}
class CreateDonor1 extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RegistrationActivity.this);
pDialog.setMessage("Creating DONOR..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
String NAME = et1.getText().toString();
String ADDRESS = et2.getText().toString();
String PHONENUMBER = et3.getText().toString();
String EMAIL = et4.getText().toString();
String CITY = et5.getText().toString();
String BLOODGROUP = et6.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("NAME", NAME));
params.add(new BasicNameValuePair("ADDRESS", ADDRESS));
params.add(new BasicNameValuePair("PHONENUMBER", PHONENUMBER));
params.add(new BasicNameValuePair("EMAIL", EMAIL));
params.add(new BasicNameValuePair("CITY", CITY));
params.add(new BasicNameValuePair("BLOODGROUP", BLOODGROUP));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_donor,
"POST", params);
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created donor
Intent i = new Intent(getApplicationContext(), SuccessfulActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
pls check the answer by commonsware in the below link
When to call activity context OR application context?
public class MainActivity extends Activity implements OnClickListener
Then in onCreate
Button b1 = (Button) findViewById(R.id.b1);
Button b2 = (Button) findViewById(R.id.b2);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
Then override onClick
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.b1 :
Intent i=new Intent(MainActivity.this,RegistrationActivity.class);
startActivity(i);
break;
case R.id.b2 :
Intent i=new Intent(MainActivity.this,SearchDirectly1Activity.class);
startActivity(i);
break;
}
}
Or
In onCreate using annonymous inner class
Button b1 = (Button) findViewById(R.id.b1);
Button b2 = (Button) findViewById(R.id.b2);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(MainActivity.this,RegistrationActivity.class);
startActivity(i);
}
});
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(MainActivity.this,SearchDirectly1Activity.class);
startActivity(i);
}
});
Make sure you have made an entry for the activities in manifest file
Do not use ApplicationContext to start activity,because application context do not ensure which activity task will use,and will throw Exception.
So you need to use Activity Context or Context from view(someView.getContext()) to start activity.
You may want to check the below link
When to call activity context OR application context?