How to solve the error like java.lang.Throwable: setStateLocked? - java

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);

Related

Parsing data or executing data Errror

I have this application the app bring data from database and store it in a list view then every record have a history i want when i click on the record in the ListView to show me the history of that record. for now i made it when i click on a record then click find id button it will give me the id of the record then i will click History to clear this ListView and showing the history of this record on the same ListView.
Screen Shot for the app1 ,
Screen Shot for the app2
Any one Can help me, my app run but when i want to show the history it don't pass this (if) i don't know why
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if(integer == 1){
ArrayAdapter<String > adapter= new ArrayAdapter<String>(c,android.R.layout.simple_list_item_1, patients );
lv.setAdapter(null);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Snackbar.make(view,patients.get(i), Snackbar.LENGTH_SHORT).show();
}
});
}else{
Toast.makeText(c,"Unable to parse data", Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
}
the PHP side
<?php
$host='127.0.0.1';
$username='root';
$password='';
$database='app';
$con =mysqli_connect($host, $username, $password, $database) or die ('unable to connect');
if (mysqli_connect_error($con))
{
echo "Failed to connect to Database ".mysqli_connect_error();
}
$patientID = $_GET['patientID'];
$query= mysqli_query($con, "SELECT * FROM history where
patientID='$patientID' ");
if ($query)
{
while ($row = mysqli_fetch_array($query))
{
$flag[]= $row;
}
print(json_encode($flag));
}
mysqli_close($con);
?>
HistoryDownloader Java Class
public class HistoryDownloader extends AsyncTask<Void, Integer, String> {
Context c;
String address;
ListView lv;
ProgressDialog progressDialog;
public HistoryDownloader(Context c, String address, ListView lv) {
this.c = c;
this.address = address;
this.lv = lv;
}
//Before the job start
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog= new ProgressDialog(c);
progressDialog.setTitle("Fetch Data");
progressDialog.setMessage("Fetching data .... Please wait ");
progressDialog.show();
}
#Override
protected String doInBackground(Void... strings) {
String data= downloadData();
return data;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
if (s != null){
HistoryParser h= new HistoryParser(c,lv,s);
h.execute();
}else{
Toast.makeText(c, "Unable to download data ", Toast.LENGTH_SHORT).show();
}
}
private String downloadData(){
//connect and get a stream
InputStream is= null;
String line =null;
try{
URL url = new URL(address);
HttpURLConnection con= (HttpURLConnection) url.openConnection();
is =new BufferedInputStream( con.getInputStream());
BufferedReader br= new BufferedReader(new InputStreamReader(is));
StringBuffer sb= new StringBuffer() ;
if(br !=null){
while((line=br.readLine()) !=null){
sb.append(line+"\n");
}
}
else{
return null;
}
return sb.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
HistoryParser java Class
public class HistoryParser extends AsyncTask<Void, Integer, Integer> {
String lls;
Context c;
ListView lv;
String data;
ArrayList<String > patients= new ArrayList<>();
ProgressDialog progressDialog;
public HistoryParser (Context c, ListView lv, String data) {
this.c = c;
this.lv = lv;
this.data = data;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog= new ProgressDialog(c);
progressDialog.setTitle("Parser");
progressDialog.setMessage("Parsing the data ... please wait");
progressDialog.show();
}
#Override
protected Integer doInBackground(Void... voids) {
return this.histoParse();
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if(integer == 1){
ArrayAdapter<String > adapter= new ArrayAdapter<String>(c,android.R.layout.simple_list_item_1, patients );
lv.setAdapter(null);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Snackbar.make(view,patients.get(i), Snackbar.LENGTH_SHORT).show();
}
});
}else{
Toast.makeText(c,"Unable to parse data", Toast.LENGTH_SHORT).show();
}
progressDialog.dismiss();
}
// parse the reciv
private int histoParse (){
try {
//adding the data to json aray first
JSONArray js= new JSONArray(data);
//create json object to hold a singel item
JSONObject jo= null;
patients.clear();
// loop the array
for(int i=0 ;i<js.length();i++){
jo= js.getJSONObject(i);
//retriving the name
//TODO: write the strring depend on the column name in the database
// write the strring depend on the column name in the database
String case1=jo.getString("case1");
/* String case2=jo.getString("case2");
String case3=jo.getString("Case3");
String case4=jo.getString("Case4");
String case5=jo.getString("Case5");
String case6=jo.getString("Case6");
String case7=jo.getString("Case7");
String case8=jo.getString("Case8");
String case9=jo.getString("Case9");
String case10=jo.getString("Case10");
String trt1=jo.getString("trt1");
String trt2=jo.getString("trt2");
String trt3=jo.getString("trt3");
String trt4=jo.getString("trt4");
String trt5=jo.getString("trt5");
String trt6=jo.getString("trt6");
String trt7=jo.getString("trt7");
String trt8=jo.getString("trt8");
String trt9=jo.getString("trt9");
String trt10=jo.getString("trt10");
//add it to our array list
patients.add("Patient History");
patients.add("");
patients.add("Cases");
patients.add("");
*/ patients.add(case1);
/* patients.add(case2);
players.add(case3);
players.add(case4);
players.add(case5);
players.add(case6);
players.add(case7);
players.add(case8);
players.add(case9);
players.add(case10);
players.add("");
players.add("Treatments");
players.add("");
players.add(trt1);
players.add(trt2);
players.add(trt3);
players.add(trt4);
players.add(trt5);
players.add(trt6);
players.add(trt7);
players.add(trt8);
players.add(trt9);
players.add(trt10);
*/
}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
Main Class Java
public class MainActivity extends AppCompatActivity {
Context context;
String url="http://10.0.2.2/Android/Fetch.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final TextView textView= (TextView) findViewById(R.id.textView);
final ListView lv=(ListView) findViewById(R.id.lv);
final Downloader d= new Downloader(this,url,lv);
String urlHistory="http://10.0.2.2/Android/History.php?patientID="+textView.getText().toString().trim();
final HistoryDownloader dd= new HistoryDownloader(this,urlHistory,lv);
final Button btn= (Button ) findViewById(R.id.button);
final Button btn2=(Button) findViewById(R.id.button2);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
lv.setAdapter(null);
//String kk=textView.getText().toString().trim();
dd.execute();
if(textView.getText() != ""){
}else{
}
}
});
i did not use Transmitting Network Data Volley thats why im getting :)

sent parameter to adapter in same class android

I have public class StudioDetail (main class) and in StudioDetail I generate private class SendfeedbackKelas like this :
private class SendfeedbackKelas extends AsyncTask<String, Void, String> {
private static final String LOG_TAG = "CariKelas";
Bundle extras = getIntent().getExtras();
final String token= extras.getString("TOKEN");
final String idstudio= extras.getString("STUDIO_ID");
#Override
protected String doInBackground(String... params) {
String date = params[0];
Utils.log("params 1:" + date);
// do above Server call here
kelasstudioList = new ArrayList<KelasStudioModel>();
String responseString = null;
final String url_kelas_studio = Constant.URI_BASE_STUDIO + idstudio + "/class" + "?date=" + date + "&token=" + token;
Utils.log("url kelas studio:"+ url_kelas_studio);
try
{
runOnUiThread(new Runnable() {
public void run() {
new JSONAsyncTask().execute(url_kelas_studio);
ListView listview = (ListView) findViewById(R.id.listView1);
adapter = new ClassSAdapter(context, R.layout.jadwalstudio_info, kelasstudioList);
listview.setAdapter(adapter);
}
});
}
catch (Exception e)
{
/*Toast.makeText(context,
"user not registered", Toast.LENGTH_SHORT).show();*/
Log.e(LOG_TAG, String.format("Error during login: %s", e.getMessage()));
}
return "processing";
}
protected void onPostExecute(Boolean result) {
//dialog.cancel();
}
}
that called ClassSAdapter like this :
private class ClassSAdapter extends ArrayAdapter<KelasStudioModel> {
final Context context = getContext();
ArrayList<KelasStudioModel> kelasstudioList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public ClassSAdapter(Context context, int resource, ArrayList<KelasStudioModel> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
kelasstudioList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View.OnClickListener listener1 = new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (int)v.getTag();
// do stuff based on position or kelasList.get(position)
// you can call mActivity.startActivity() if you need
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(R.layout.dialog_popup_pesan_kelas);
closedialog = (ImageView) dialog.findViewById(R.id.closeDialog);
// if button is clicked, close the custom dialog
closedialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
/*studio_name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, StudioDetail.class);
startActivity(intent);
}
});*/
dialog.show();
}
};
View.OnClickListener listener2 = new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (int)v.getTag();
// do stuff based on position or kelasList.get(position)
// you can call mActivity.startActivity() if you need
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(R.layout.dialog_popup_pelatih);
/*final String url_studio_image = Constant.URI_FRONTEND + "vendor_trainer/20150821052441-tanda-tanya.jpg";
Utils.log("url_studio_image: " + url_studio_image);
new DownloadImageTask((ImageView) dialog.findViewById(R.id.class_image_pelatih)).execute(url_studio_image);*/
closedialog = (ImageView) dialog.findViewById(R.id.closeDialog);
// if button is clicked, close the custom dialog
closedialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
};
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.kelas = (TextView) v.findViewById(R.id.kelas);
holder.waktu = (TextView) v.findViewById(R.id.waktu);
holder.pelatih = (TextView) v.findViewById(R.id.pelatih);
// set OnClickListeners
holder.kelas.setOnClickListener(listener1);
holder.pelatih.setOnClickListener(listener2);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
//holder.imageview.setImageResource(R.drawable.promo_1);
holder.kelas.setText(kelasstudioList.get(position).getKelas());
holder.waktu.setText(kelasstudioList.get(position).getWaktu());
holder.pelatih.setText(kelasstudioList.get(position).getPelatih());
// set tags
holder.kelas.setTag(position);
holder.waktu.setTag(position);
holder.pelatih.setTag(position);
return v;
}
private class ViewHolder {
public TextView kelas;
public TextView waktu;
public TextView pelatih;
}
}
I want to sent some parameter like this from class JSONAsyncTask to private class ClassSAdapter on View.OnClickListener listener1 and View.OnClickListener listener2 :
final String startdate=object.getString("startdate");
final String masterclass_name=Html.fromHtml((String) object.getString("masterclass_name")).toString();
final String enddate=object.getString("enddate");
final String trainer_name=Html.fromHtml((String) object.getString("trainer_name")).toString();
How to sent that parameter?
As information here is JSONAsynTask class:
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
private static final String TAG_CLASSES = "classes";
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(context);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String responseAsText = EntityUtils.toString(entity);
Utils.log("daftar isi classes: " + responseAsText);
JSONObject jsonObj = new JSONObject(responseAsText);
// Getting JSON Array node
JSONArray classes = jsonObj.getJSONArray(TAG_CLASSES);
for(int i=0;i<classes.length();i++){
//HashMap<String, String> promo = new HashMap<String, String>();
JSONObject object = classes.getJSONObject(i);
final String startdate=object.getString("startdate");
final String masterclass_name=Html.fromHtml((String) object.getString("masterclass_name")).toString();
final String enddate=object.getString("enddate");
final String trainer_name=Html.fromHtml((String) object.getString("trainer_name")).toString();
KelasStudioModel actor = new KelasStudioModel();
String starttime = parseDateToHis((String) object.getString("startdate")).toString();
String endtime = parseDateToHis((String) object.getString("enddate")).toString();
actor.setKelas(Html.fromHtml((String) object.getString("masterclass_name")).toString());
actor.setWaktu(starttime + "-" + endtime);
actor.setPelatih(object.getString("trainer_name"));
kelasstudioList.add(actor);
}
return true;
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result == false){
Toast.makeText(context, "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}else{
}
}
}
listener 1 and listener 2 called different dialog.

search filter for Listview [duplicate]

I'm a beginner, I'm creating a job search app which shows job infomation as listview where the data is from WAMP server database. I encounter a problem : Cannot resolve method 'getStringArrayList' , when I'm making a search filter for this Listview. Please see line 11 of SearchFilter.java. Could anyone help? thank you very much!
SearchFilter.java
public class SearchFilter extends ListActivity {
private EditText filterText = null;
ArrayAdapter<String> adapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
getStringArrayList())); ***<<<<< this line !***
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
}
};
#Override
protected void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
}
MainActivity.java
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://192.168.0.102/get_json_select_all.php";
// JSON Node names
private static final String TAG_INFO = "info";
private static final String TAG_POSTNAME = "PostName";
private static final String TAG_LOCATION = "Location";
private static final String TAG_SALARY = "Salary";
private static final String TAG_RESPONSIBILITY = "Responsibility";
private static final String TAG_COMPANY = "Company";
private static final String TAG_CONTACT = "Contact";
// contacts JSONArray
JSONArray infos = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> infoList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
infoList = new ArrayList<HashMap<String, String>>();
final ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.PostName))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.Location))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.Salary))
.getText().toString();
HashMap<String, String> info = new HashMap<String, String>();
info=(HashMap<String, String>)lv.getAdapter().getItem(position);
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_POSTNAME, name);
in.putExtra(TAG_LOCATION, cost);
in.putExtra(TAG_SALARY, description);
in.putExtra(TAG_RESPONSIBILITY, info.get(TAG_RESPONSIBILITY));
in.putExtra(TAG_COMPANY, info.get(TAG_COMPANY));
in.putExtra(TAG_CONTACT, info.get(TAG_CONTACT));
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
infos = jsonObj.getJSONArray(TAG_INFO);
// looping through All Contacts
for (int i = 0; i < infos.length(); i++) {
JSONObject c = infos.getJSONObject(i);
String id = c.getString(TAG_POSTNAME);
String name = c.getString(TAG_LOCATION);
String email = c.getString(TAG_SALARY);
String address = c.getString(TAG_RESPONSIBILITY);
String gender = c.getString(TAG_COMPANY);
// Phone node is JSON Object
String mobile = c.getString(TAG_CONTACT);
// tmp hashmap for single contact
HashMap<String, String> info = new HashMap<String, String>();
// adding each child node to HashMap key => value
info.put(TAG_POSTNAME, id);
info.put(TAG_LOCATION, name);
info.put(TAG_SALARY, email);
info.put(TAG_RESPONSIBILITY, address);
info.put(TAG_COMPANY, gender);
info.put(TAG_CONTACT, mobile);
// adding contact to contact list
infoList.add(info);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
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
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, infoList,
R.layout.list_item, new String[] { TAG_POSTNAME, TAG_LOCATION,
TAG_SALARY }, new int[] { R.id.PostName,
R.id.Location, R.id.Salary });
setListAdapter(adapter);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return (super.onCreateOptionsMenu(menu));
}
}
activity_main.xml
<EditText android:id="#+id/search_box"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search Jobs"
android:inputType="text"
android:maxLines="1"/>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
getStringArrayList is a method on Bundle (such as savedInstanceState). There's no such method in Activity. Hope that helps.
Currently your infoList is an ArrayList>, something that is harder to pass directly to an activity. So find a way to represent it as an ArrayList, or find a more suitable datatype supported by Intent's putExtra-methods. Here below is a suggested solution using an ArrayList.
Passing the data into the activity with the Intent allows you to get it back in your SearchFilter. In the calling activity put something like this:
Intent i = new Intent(this, SearchFilter.class);
i.putStringArrayListExtra("com.yourpackagename.here.keynamehere", aStringArrayList);
In SearchFilter.java, put something like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
Intent startingIntent = getIntent();
ArrayList<String> arrayList = new ArrayList<String>();
if (startingIntent != null) {
arrayList = startingIntent.getStringArrayList("com.yourpackagename.here.keynamehere");
}
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
arrayList));
}

how to display details of single item of list in another activity from url (json data)?

I have written a program to display the list of json data from a url which has an image and 5 textviews which is displaying perfectly.
Url : https://itunes.apple.com/search?term=jack+johnson&limit=50.
When i click on an item from the list i want to display the details of that item in another activity based on the track-id
Url : https://itunes.apple.com/lookup?id=659234741
So when i click on the item the details are getting displayed in the textview , but by default it is displaying the details of id = 659234741 for some items or in short the details does not match.
Need some help to figure out the problem
My Code :
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultsList = new ArrayList<HashMap<String, String>>();
lv = getListView();
// Calling async task to get json
new GetTunesDetails().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetTunesDetails extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
tunes = jsonObj.getJSONArray(TAG_RESULT);
// looping through All Products
for (int i = 0; i < tunes.length(); i++) {
JSONObject c = tunes.getJSONObject(i);
artworkImage = c.getString("artworkUrl100");
wrapperType = c.getString("wrapperType");
artistName = c.getString("artistName");
collectionName = c.getString("collectionName");
trackName = c.getString("trackName");
collectionPrice = c.getString("collectionPrice");
trackId = c.getString("trackId");
// tmp hashmap for single contact
HashMap<String, String> tunesMap = new HashMap<String,
String>();
// adding each child node to HashMap key => value
// contact.put(TAG_ID, firstname);
tunesMap.put(TAG_ARTWORK_IMAGE, artworkImage);
tunesMap.put(TAG_WRAPPER_TYPE, wrapperType);
tunesMap.put(TAG_ARTIST_NAME, artistName);
tunesMap.put(TAG_COLLECTION_NAME, collectionName);
tunesMap.put(TAG_TRACK_NAME, trackName);
tunesMap.put(TAG_COLLECTION_PRICE, collectionPrice);
tunesMap.put(TAG_TRACK_ID, trackId);
// adding contact to contact list
resultsList.add(tunesMap);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, resultsList);
// Set the adapter to the ListView
lv.setAdapter(adapter);
}
}
ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
int position;
TextView wrapperType, artistName, collectionName, trackName,
collectionPrice;
ImageView artworkImage;
public ListViewAdapter(Context context, ArrayList<HashMap<String, String>>
arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#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
// this.position = position;
inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.custom_row, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
wrapperType = (TextView) itemView.findViewById(R.id.wrapperType);
artistName = (TextView) itemView.findViewById(R.id.artistName);
collectionName = (TextView) itemView.findViewById(R.id.collectionName);
trackName = (TextView) itemView.findViewById(R.id.trackName);
collectionPrice = (TextView)
itemView.findViewById(R.id.collectionPrice);
// Locate the ImageView in listview_item.xml
artworkImage = (ImageView) itemView.findViewById(R.id.artworkImage);
// Capture position and set results to the TextViews
wrapperType.setText(resultp.get(MainActivity.TAG_WRAPPER_TYPE));
artistName.setText(resultp.get(MainActivity.TAG_ARTIST_NAME));
collectionName.setText(resultp.get(MainActivity.TAG_COLLECTION_NAME));
trackName.setText(resultp.get(MainActivity.TAG_TRACK_NAME));
collectionPrice.setText(resultp.get(MainActivity.TAG_COLLECTION_PRICE));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.TAG_ARTWORK_IMAGE),
artworkImage);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) { // TODO Auto-generated method
Toast.makeText(context, "Clicked at position " + position,
Toast.LENGTH_LONG).show();
Intent intent = new Intent(context, SingleTrack.class);
intent.putExtra("track_image",
resultp.get(MainActivity.TAG_ARTWORK_IMAGE));
intent.putExtra("wrapper_type",
resultp.get(MainActivity.TAG_WRAPPER_TYPE));
intent.putExtra("artistName",
resultp.get(MainActivity.TAG_ARTIST_NAME));
intent.putExtra("collectionName",
resultp.get(MainActivity.TAG_COLLECTION_NAME));
intent.putExtra("trackName",
resultp.get(MainActivity.TAG_TRACK_NAME));
intent.putExtra("collectionPrice",
resultp.get(MainActivity.TAG_COLLECTION_PRICE));
intent.putExtra("trackId",
resultp.get(MainActivity.TAG_TRACK_ID));
context.startActivity(intent);
}
});
return itemView;
}
SingleTrack.java : This is the class where i displaying the details on single item click
public class SingleTrack extends Activity {
// URL to get contacts JSON
private static String url = "";
// JSON Node names
static final String TAG_RESULT = "results";
static final String TAG_ARTWORK_IMAGE = "artworkUrl100";
static final String TAG_WRAPPER_TYPE = "wrapperType";
static final String TAG_ARTIST_NAME = "artistName";
static final String TAG_COLLECTION_NAME = "collectionName";
static final String TAG_TRACK_NAME = "trackName";
static final String TAG_COLLECTION_PRICE = "collectionPrice";
static final String TAG_TRACK_ID = "trackId";
// contacts JSONArray
JSONArray tracks = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> singleTrackDetails;
ProgressDialog pDialog;
String passedData1, passedData2, passedData3, passedData4, passedData5,
passedData6, passedData7;
TextView wrapperTypeText, artistNameText, collectionNameText, trackNameText,
collectionPriceText;
ImageView trackImage;
String artworkImage, wrapperType, artistName, collectionName, trackName,
collectionPrice, trackId;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.single_track);
wrapperTypeText = (TextView) findViewById(R.id.wrapperType1);
artistNameText = (TextView) findViewById(R.id.artistName1);
collectionNameText = (TextView) findViewById(R.id.collectionName1);
trackNameText = (TextView) findViewById(R.id.trackName1);
collectionPriceText = (TextView) findViewById(R.id.collectionPrice);
trackImage = (ImageView) findViewById(R.id.artworkImage1);
passedData1 = getIntent().getStringExtra("track_image");
passedData2 = getIntent().getStringExtra("wrapper_type");
passedData3 = getIntent().getStringExtra("artistName");
passedData4 = getIntent().getStringExtra("collectionName");
passedData5 = getIntent().getStringExtra("trackName");
passedData6 = getIntent().getStringExtra("collectionPrice");
passedData7 = getIntent().getStringExtra("trackId");
singleTrackDetails = new ArrayList<HashMap<String, String>>();
// url
url = "https://itunes.apple.com/lookup?id=" + passedData7;
// Calling async task to get json
new GetSingleTrackDetails().execute();
}
class GetSingleTrackDetails extends AsyncTask<String, Void, String> {
private JSONObject jsonObj;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(SingleTrack.this);
pDialog.setMessage("Loading Track Details...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
tracks = jsonObj.getJSONArray(TAG_RESULT);
// looping through All Products
for (int i = 0; i < tracks.length(); i++) {
JSONObject c = tracks.getJSONObject(i);
artworkImage = c.getString("artworkUrl100");
wrapperType = c.getString("wrapperType");
artistName = c.getString("artistName");
collectionName = c.getString("collectionName");
trackName = c.getString("trackName");
collectionPrice = c.getString("collectionPrice");
trackId = c.getString("trackId");
// tmp hashmap for single contact
HashMap<String, String> tunesMap = new HashMap<String,
String>();
// adding each child node to HashMap key => value
// contact.put(TAG_ID, firstname);
tunesMap.put(TAG_ARTWORK_IMAGE, artworkImage);
tunesMap.put(TAG_WRAPPER_TYPE, wrapperType);
tunesMap.put(TAG_ARTIST_NAME, artistName);
tunesMap.put(TAG_COLLECTION_NAME, collectionName);
tunesMap.put(TAG_TRACK_NAME, trackName);
tunesMap.put(TAG_COLLECTION_PRICE, collectionPrice);
tunesMap.put(TAG_TRACK_ID, trackId);
// adding contact to contact list
singleTrackDetails.add(tunesMap);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
wrapperTypeText.setText(wrapperType);
artistNameText.setText(artistName);
collectionNameText.setText(collectionName);
trackNameText.setText(trackName);
collectionPriceText.setText(collectionPrice);
}
}
Thank you
The problem is that you are initializing the resultp each element in your getView method, so therefore the last id/element of the listview adapter's data will be considered as the resultp.
Im sure that the id 659234741 is the last element, which will always be the id for each onclick that would happen.
A solution for this is to create a final resultp within your getView method instead of having just one global resultp.
final HashMap<String, String> resultp = data.get(position);

ListView Doesn't display anymore than 8 ImageViews

I am decoding jpeg images from a server request I get using json. I display them with a custom ListView Adapter along with a little text.
The images display correctly for the first 8 ImageViews in the ListView, however, after that it will no longer display the image (it will display the text). For example, if I have a total of 10 images, the last two images will not show in the ListView, but if I delete the first 2 images, the last two will show, so there is no concern about retrieving the actual images.
On my main activity (NotesActivity) I have a button that goes to another activity which does an asyntask, and in that async task in the onPostExecute, it returns back to the main activity where it should show the updated list (and it does, unless there are more than 8 images).
I don't know where to begin, any suggestions?
My Activity that contains the ListView
public class NotesActivity extends Activity implements OnClickListener {
String key = "NOTES";
String key2 = "UPDATE_NOTES";
Gson gson = new Gson();
// Notes myNotes = new Notes();
NotesList myNotes = new NotesList();
String bId;
String res = null;
EditText notes;
Button save;
private Button createNote;
private int position;
private String type;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notes_layout);
createNote = (Button) findViewById(R.id.notes_layout_btn_createNote);
Bundle bundle = this.getIntent().getExtras();
position = bundle.getInt("position");
type = bundle.getString("type");
//
if (type.equals("LISTINGS")) {
Listings it = ListingsFragment.myListings.getListings().get(
position);
bId = it.getBID();
notes = (EditText) findViewById(R.id.notes);
}
//
if (type.equals("SHARED")) {
Listings it = SharedFragment.myShared.getListings().get(position);
bId = it.getBID();
notes = (EditText) findViewById(R.id.notes);
}
GetNotes getNotes = new GetNotes();
try {
NotesList copy = new NotesList();
getNotes.execute(key, bId).get();
for (int j = 0; j < myNotes.getNotes().size(); j++) {
Notes note = myNotes.getNotes().get(j);
System.out.println("Removed value: " + note.getIsRemoved());
if (note.getIsRemoved() == null) {
copy.getNotes().add(note);
}
}
NotesAdapter adapter = new NotesAdapter(this, R.layout.note_row,
copy.getNotes());
ListView lv = (ListView) findViewById(R.id.notes_layout_lv_notesList);
lv.setAdapter(adapter);
} catch (Exception e) {
}
createNote.setOnClickListener(this);
}
private class GetNotes extends AsyncTask<String, String, NotesList> {
#Override
protected NotesList doInBackground(String... things) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("key", things[0]));
postParameters.add(new BasicNameValuePair("bId", things[1]));
// String valid = "1";
String response = null;
try {
response = CustomHttpClient.executeHttpPost(
"http://propclip.dev/mobile.php", postParameters);
res = response.toString();
// System.out.println("This is the response " + res);
// res = res.trim();
// res= res.replaceAll("\\s+","");
// error.setText(res);
// System.out.println(res);
myNotes = gson.fromJson(res, NotesList.class);
// System.out.println(res);
} catch (Exception e) {
res = e.toString();
}
return myNotes;
}
#Override
protected void onPostExecute(NotesList res) {
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.notes_layout_btn_createNote:
ProfileDataSource datasource = new ProfileDataSource(this);
datasource.open();
PropClipGlobal pcg = datasource.getUserIdenity();
Intent intent = new Intent(this, NewNoteActivity.class);
intent.putExtra("bId", bId);
intent.putExtra("uId", pcg.getUID());
intent.putExtra("username", pcg.getEm());
intent.putExtra("position", position);
intent.putExtra("type", type);
startActivity(intent);
}
}
}
My custom adapter
public class NotesAdapter extends ArrayAdapter<Notes> {
List<Notes> notes;
Context context;
public NotesAdapter(Context context, int resource, List<Notes> notes) {
super(context, resource, notes);
this.notes = notes;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.note_row, null);
}
Notes note = notes.get(position);
ImageView icon = (ImageView) v.findViewById(R.id.note_row_icon);
TextView name = (TextView) v.findViewById(R.id.note_row_name);
TextView message = (TextView) v.findViewById(R.id.note_row_message);
TextView date = (TextView) v.findViewById(R.id.note_row_date);
String input = note.getNoteDate();
SimpleDateFormat inputDf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat outputDf = new SimpleDateFormat("dd, yyyy");
SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
Date myDate = null;
try {
myDate = inputDf.parse(input);
} catch (ParseException e) {
e.printStackTrace();
}
String month = monthFormat.format(myDate);
date.setText(getMonth(Integer.parseInt(month)) + " "
+ outputDf.format(myDate));
message.setText(note.getNote());
name.setText(note.getFirstName() + " " + note.getLastName());
// System.out.println(p.getFileData());
byte[] imageAsBytes = Base64.decode(note.getFileData().getBytes(),
position);
icon.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0,
imageAsBytes.length));
System.out.println(note.getFileData());
return v;
}
public String getMonth(int month) {
return new DateFormatSymbols().getMonths()[month - 1];
}
}
Activity which eventually goes to the main activity (NotesActivity)
public class NewNoteActivity extends Activity implements OnClickListener {
private String uId;
private String bId;
private String username;
private String response;
private String key = "UPDATE_NOTES";
private Button submit;
private EditText note;
private int position;
private String type;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_note);
submit = (Button) findViewById(R.id.activity_new_note_btn_submit);
note = (EditText) findViewById(R.id.activity_new_note_et_note);
Intent intent = getIntent();
bId = intent.getStringExtra("bId");
uId = intent.getStringExtra("uId");
username = intent.getStringExtra("username");
position = intent.getIntExtra("position", 0);
type = intent.getStringExtra("type");
submit.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.new_note, menu);
return true;
}
private class UpdateNotes extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... values) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("key", values[0]));
postParameters.add(new BasicNameValuePair("bId", values[1]));
postParameters.add(new BasicNameValuePair("uId", values[2]));
postParameters.add(new BasicNameValuePair("username", values[3]));
postParameters.add(new BasicNameValuePair("note", values[4]));
String response = null;
try {
response = CustomHttpClient.executeHttpPost(
"http://propclip.dev/mobile.php", postParameters);
response = response.toString();
} catch (Exception e) {
response = e.toString();
}
return null;
}
#Override
protected void onPostExecute(String response) {
Intent intent = new Intent(getApplicationContext(),
NotesActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("position", position);
intent.putExtra("type", type);
startActivity(intent);
Toast toast = Toast.makeText(getApplicationContext(),"Added note!", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
#Override
public void onClick(View v) {
String noteMessage = note.getText().toString();
UpdateNotes updateNotes = new UpdateNotes();
updateNotes.execute(key, bId, uId, username, noteMessage);
}
}

Categories

Resources