Simple Todo android app with mlab dont add or edit - java

I created an application with android studio and connected it to mLab, the application is a simple task list (toDo App). I can see perfectly the records of the mLab database. The problem is that I can not edit or create new records. Deleting works perfects, If I delete them, they are removed from the app and mLab. I do not see any visible error.
Anyone can help me to spot the error?
i leave here the repo from my project TodoApp
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView lstViewItems;
Button btnAdd, btnEdit, btnDelete;
EditText edtItem;
item itemSelected=null;
List<item> items = new ArrayList<item>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstViewItems = (ListView)findViewById(R.id.lstView);
btnAdd = (Button)findViewById(R.id.btnAddItem);
btnEdit = (Button)findViewById(R.id.btnEdit);
btnDelete = (Button)findViewById(R.id.btnDelete);
edtItem = (EditText) findViewById(R.id.edtItem);
//LOAD DATA WHEN APP OPENED
new GetData().execute(Common.getAddressAPI());
lstViewItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
itemSelected = items.get(position);
//SET TEXT TO EDIT TEXT
edtItem.setText(itemSelected.getItem());
}
});
//ADD EVENT TO BUTTON
btnAdd.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
new PostData(edtItem.getText().toString()).execute(Common.getAddressAPI());
}
});
//BECAUSE THIS FUNCTION WE NEED PARAMETER ITEMSELECTED, SO WE NEED SET ITEMSELECTED
//WHEN USER CLICK ON ITEM IN LISTVIEW
btnEdit.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
}
});
btnDelete.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
new DeleteData(itemSelected).execute(Common.getAddressSingle(itemSelected));
}
});
}
//FUNCTION PROCESS DATA
class GetData extends AsyncTask<String, Void, String>{
ProgressDialog pd = new ProgressDialog(MainActivity.this);
#Override
protected void onPreExecute(){
super.onPreExecute();
//Pre process
pd.setTitle("Please wait...");
pd.show();
}
#Override
protected String doInBackground(String... params){
// RUNNING PROCCESS..
String stream = null;
String urlString = params[0];
HTTPDataHandler http = new HTTPDataHandler();
stream = http.GetHTTPData(urlString);
return stream;
}
#Override
protected void onPostExecute(String s){
super.onPostExecute(s);
//Done process
//WE WILL USE GSON TO PARSE JSON TO CLASS
Gson gson = new Gson();
Type listType = new TypeToken<List<item>>(){}.getType();
items=gson.fromJson(s,listType); // PARSE TO LIST
CustomAdapter adapter = new CustomAdapter(getApplicationContext(),items); // CREATE ADAPTER
lstViewItems.setAdapter(adapter); // SET ADAPTER TO LIST VIEW
pd.dismiss();
}
}
// FUNCTION TO ADD NEW ITEM
class PostData extends AsyncTask<String,String,String> {
ProgressDialog pd = new ProgressDialog(MainActivity.this);
String item;
public PostData(String item){
this.item = item;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd.setTitle("Please wait...");
pd.show();
}
#Override
protected String doInBackground(String... params) {
String urlString = params[0];
HTTPDataHandler hh = new HTTPDataHandler();
String json="(\"item\":\""+item+"\")";
hh.PostHTTPData(urlString,json);
return "";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//REFRESH DATA
new GetData().execute(Common.getAddressAPI());
pd.dismiss();
}
}
// FUNCTION TO EDIT ITEM
class PutData extends AsyncTask<String,String,String> {
ProgressDialog pd = new ProgressDialog(MainActivity.this);
String item;
public PutData(String item){
this.item = item;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd.setTitle("Please wait...");
pd.show();
}
#Override
protected String doInBackground(String... params) {
String urlString = params[0];
HTTPDataHandler hh = new HTTPDataHandler();
String json="(\"item\":\""+item+"\")";
hh.PutHTTPData(urlString,json);
return "";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//REFRESH DATA
new GetData().execute(Common.getAddressAPI());
pd.dismiss();
}
}
// FUNCTION TO DELETE ITEM
class DeleteData extends AsyncTask<String,String,String> {
ProgressDialog pd = new ProgressDialog(MainActivity.this);
item item;
public DeleteData(item item){
this.item = item;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd.setTitle("Please wait...");
pd.show();
}
#Override
protected String doInBackground(String... params) {
String urlString = params[0];
HTTPDataHandler hh = new HTTPDataHandler();
String json="(\"item\":\""+item.getItem()+"\")";
hh.DeleteHTTPData(urlString,json);
return "";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//REFRESH DATA
new GetData().execute(Common.getAddressAPI());
pd.dismiss();
}
}
}
}

The first error is that you are sending a wrong json format so you need to change it to the right format, second you are indexing the id variable but you are noting sending it. change your json variable in the post method to :
String json = "{'item' :'" + item + "', 'id' : '"+ UUID.randomUUID().toString() +"'}";

Related

My data cannot be uploaded to mysql server database shows string cannot be converted to JSONobject

I am creating a simple android app to upload data to mysql server db, but shows error as string cannot be converted to JSON Object.
Can i make it for filtering vulgar words too?
This is for my android app, if this works fine i will use it for uploading words and meanings for my dictionary
I tried other solution.
public class MainActivity extends Activity {
private EditText etName, etMobile, etAddress;
private Button btnSubmit;
private ProgressDialog pDialog;
private JSONObject json;
private int success = 0;
private HTTPURLConnection service;
private String strname = "", strMobile = "", strAddress = "";
//Initialize webservice URL
private String path = "https://meiteiwords.000webhostapp.com/add_employee.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etName = (EditText) findViewById(R.id.etName);
etMobile = (EditText) findViewById(R.id.etMobile);
etAddress = (EditText) findViewById(R.id.etAddress);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
//Initialize HTTPURLConnection class object
service = new HTTPURLConnection();
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!etName.getText().toString().equals("") && !etMobile.getText().toString().equals("")) {
strname = etName.getText().toString();
strMobile = etMobile.getText().toString();
strAddress = etAddress.getText().toString();
//Call WebService
new PostDataTOServer().execute();
} else {
Toast.makeText(getApplicationContext(), "Please Enter all fields", Toast.LENGTH_LONG).show();
}
}
});
}
private class PostDataTOServer extends AsyncTask<Void, Void, Void> {
String response = "";
//Create hashmap Object to send parameters to web service
HashMap<String, String> postDataParams;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
postDataParams = new HashMap<String, String>();
postDataParams.put("name", strname);
postDataParams.put("mobile", strMobile);
postDataParams.put("address", strAddress);
//Call ServerData() method to call webservice and store result in response
response = service.ServerData(path, postDataParams);
try {
json = new JSONObject(response);
//Get Values from JSONobject
System.out.println("success=" + json.get("success"));
success = json.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
if (success == 1) {
Toast.makeText(getApplicationContext(), "Employee Added successfully..!", Toast.LENGTH_LONG).show();
}
}
}
}
here is my php code shows warning :
https://pastebin.com/P50EWbbR
https://pastebin.com/Aut7fFq2
You got type casting error because you try to convert String into JSONObject. You failed to sent your response as JSONObject.

Recycleview's onClick and put extra

Please help! i have a recycleview with search function(base on JSON search). i wanna click-able this recycleview(mean that getting item's ID where shown in item's view ) and then PutExtra this ID to another activity . then another activity get ID. and finally another activity post ID and get values!
this my code , somebody tell my wrongs:):
AdapterFish.java
public class AdapterFish extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private LayoutInflater inflater;
List<DataFish> data= Collections.emptyList();
DataFish current;
int currentPos=0;
public String IDHOLDER;
private Context activity;
// create constructor to initialize context and data sent from MainActivity
public AdapterFish(Context context, List<DataFish> data){
this.context=context;
inflater= LayoutInflater.from(context);
this.data=data;
}
// Inflate the layout when ViewHolder created
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflater.inflate(R.layout.container_fish, parent,false);
MyHolder holder=new MyHolder(view);
return holder;
}
// Bind data
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
// Get current position of item in RecyclerView to bind data and assign values from list
MyHolder myHolder= (MyHolder) holder;
DataFish current=data.get(position);
myHolder.company.setText(current.company);
myHolder.name.setText(current.name);
myHolder.family.setText(current.family);
myHolder.id.setText(current.id);
myHolder.id.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));
}
// return total item from List
#Override
public int getItemCount() {
return data.size();
}
public Context getActivity() {
return activity;
}
public void setActivity(Context activity) {
this.activity = activity;
}
class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView company;
TextView name;
TextView family;
TextView id;
// create constructor to get widget reference
public MyHolder(View itemView) {
super(itemView);
company= (TextView) itemView.findViewById(R.id.company);
name = (TextView) itemView.findViewById(R.id.name);
family = (TextView) itemView.findViewById(R.id.family);
id = (TextView) itemView.findViewById(R.id.id);
itemView.setOnClickListener(this);
}
// Click event for all items
#Override
public void onClick(View v) {
Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
final String ItemId = id.getText().toString().trim();
Intent intent = new Intent(context, ShowSingleRecordActivity.class);
intent.putExtra("ID", ItemId);
context.startActivity(intent);
}
}}
ShowSingleRecordActivity.java (Receiving ID)
public class ShowSingleRecordActivity extends AppCompatActivity {
HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;
// Http Url For Filter Student Data from Id Sent from previous activity.
String HttpURL = "http://192.168.137.1/namayeshgah/FilterStudentData.php";
// Http URL for delete Already Open Student Record.
String HttpUrlDeleteRecord = "http://192.168.137.1/namayeshgah/DeleteStudent.php";
String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
String ParseResult ;
HashMap<String,String> ResultHash = new HashMap<>();
String FinalJSonObject ;
TextView COMPANY,NAME,FAMILY,GENDER,EMAIL1,EMAIL2,PHONE,FAX,TELLFAX,MOBILE;
String CompanyHolder ,NameHolder,FamilyHolder,GenderHolder,Email1Holder,Email2Holder,PhoneHolder,FaxHolder,TellfaxHolder,MobileHolder;
Button UpdateButton, DeleteButton;
String TempItem;
ProgressDialog progressDialog2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_single_record);
COMPANY = (TextView)findViewById(R.id.ncompany);
NAME = (TextView)findViewById(R.id.nname);
FAMILY=(TextView)findViewById(R.id.nfamily);
GENDER =(TextView)findViewById(R.id.ngender);
EMAIL1= (TextView)findViewById(R.id.nemail1);
EMAIL2= (TextView)findViewById(R.id.nemail2);
PHONE= (TextView)findViewById(R.id.nphone);
FAX = (TextView)findViewById(R.id.nfax);
TELLFAX = (TextView)findViewById(R.id.ntellfax);
MOBILE = (TextView)findViewById(R.id.nmobile);
UpdateButton = (Button)findViewById(R.id.buttonUpdate);
DeleteButton = (Button)findViewById(R.id.buttonDelete);
//Receiving the ListView Clicked item value send by previous activity.
TempItem = getIntent().getStringExtra("ID");
//Calling method to filter Student Record and open selected record.
HttpWebCall(TempItem);
UpdateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ShowSingleRecordActivity.this,UpdateActivity.class);
// Sending Student Id, Name, Number and Class to next UpdateActivity.
intent.putExtra("Id", TempItem);
intent.putExtra("company",CompanyHolder );
intent.putExtra("name", NameHolder);
intent.putExtra("family",FamilyHolder );
intent.putExtra("gender",GenderHolder );
intent.putExtra("email1",Email1Holder );
intent.putExtra("email2",Email2Holder );
intent.putExtra("phone",PhoneHolder );
intent.putExtra("fax",FaxHolder );
intent.putExtra("tellfax",TellfaxHolder );
intent.putExtra("mobile",MobileHolder );
startActivity(intent);
// Finishing current activity after opening next activity.
finish();
}
});
// Add Click listener on Delete button.
DeleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Calling Student delete method to delete current record using Student ID.
StudentDelete(TempItem);
}
});
}
// Method to Delete Student Record
public void StudentDelete(final String StudentID) {
class StudentDeleteClass extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog2 = ProgressDialog.show(ShowSingleRecordActivity.this, "Loading Data", null, true, true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
progressDialog2.dismiss();
Toast.makeText(ShowSingleRecordActivity.this, httpResponseMsg.toString(), Toast.LENGTH_LONG).show();
finish();
}
#Override
protected String doInBackground(String... params) {
// Sending STUDENT id.
hashMap.put("StudentID", params[0]);
finalResult = httpParse.postRequest(hashMap, HttpUrlDeleteRecord);
return finalResult;
}
}
StudentDeleteClass studentDeleteClass = new StudentDeleteClass();
studentDeleteClass.execute(StudentID);
}
//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem){
class HttpWebCallFunction extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(ShowSingleRecordActivity.this,"Loading Data",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
//Storing Complete JSon Object into String Variable.
FinalJSonObject = httpResponseMsg ;
//Parsing the Stored JSOn String to GetHttpResponse Method.
new GetHttpResponse(ShowSingleRecordActivity.this).execute();
}
#Override
protected String doInBackground(String... params) {
ResultHash.put("StudentID",params[0]);
ParseResult = httpParse.postRequest(ResultHash, HttpURL);
return ParseResult;
}
}
HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();
httpWebCallFunction.execute(PreviousListViewClickedItem);
}
// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
try
{
if(FinalJSonObject != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonObject);
JSONObject jsonObject;
for(int i=0; i<jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
// Storing Student Name, Phone Number, Class into Variables.
CompanyHolder = jsonObject.getString("company");
NameHolder = jsonObject.getString("name");
FamilyHolder= jsonObject.getString("family");
GenderHolder= jsonObject.getString("gender");
Email1Holder = jsonObject.getString("email1");
Email2Holder = jsonObject.getString("email2");
PhoneHolder = jsonObject.getString("phone");
FaxHolder = jsonObject.getString("fax");
TellfaxHolder = jsonObject.getString("tellfax");
MobileHolder = jsonObject.getString("mobile");
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
// Setting Student Name, Phone Number, Class into TextView after done all process .
COMPANY.setText(CompanyHolder);
NAME.setText(NameHolder);
FAMILY.setText(FamilyHolder);
GENDER.setText(GenderHolder);
EMAIL1.setText(Email1Holder);
EMAIL2.setText(Email2Holder);
PHONE.setText(PhoneHolder);
FAX.setText(FaxHolder);
TELLFAX.setText(TellfaxHolder);
MOBILE.setText(MobileHolder);
}
}
and Searching.java
public class searching extends AppCompatActivity {
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVFish;
private AdapterFish mAdapter;
SearchView searchView = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searching);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// adds item to action bar
getMenuInflater().inflate(R.menu.search_main, menu);
// Get Search item from action bar and Get Search service
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager) searching.this.getSystemService(Context.SEARCH_SERVICE);
if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(searching.this.getComponentName()));
searchView.setIconified(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
// Every time when you press search button on keypad an Activity is recreated which in turn calls this function
#Override
protected void onNewIntent(Intent intent) {
// Get search query and create object of class AsyncFetch
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
if (searchView != null) {
searchView.clearFocus();
}
new AsyncFetch(query).execute();
}
}
// Create class AsyncFetch
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(searching.this);
HttpURLConnection conn;
URL url = null;
String searchQuery;
public AsyncFetch(String searchQuery){
this.searchQuery=searchQuery;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your php file resides
url = new URL("http://192.168.137.1/namayeshgah/search/fish-search.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput to true as we send and recieve data
conn.setDoInput(true);
conn.setDoOutput(true);
// add parameter to our above url
Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return("Connection error");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
List<DataFish> data=new ArrayList<>();
pdLoading.dismiss();
if(result.equals("no rows")) {
Toast.makeText(searching.this, "No Results found for entered query", Toast.LENGTH_LONG).show();
}else{
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataFish fishData = new DataFish();
fishData.company = json_data.getString("company");
fishData.name = json_data.getString("name");
fishData.family = json_data.getString("family");
fishData.id = json_data.getString("id");
data.add(fishData);
}
// Setup and Handover data to recyclerview
mRVFish = (RecyclerView) findViewById(R.id.fishPriceList);
mAdapter = new AdapterFish(searching.this, data);
mRVFish.setAdapter(mAdapter);
mRVFish.setLayoutManager(new LinearLayoutManager(searching.this));
} catch (JSONException e) {
// You to understand what actually error is and handle it appropriately
Toast.makeText(searching.this, e.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(searching.this, result.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
Try this
#Override
public void onClick(View v) {
DataFish newCurrent=data.get(getAdapterPosition());
Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
final String ItemId = newCurrent.id;
Intent intent = new Intent(context, ShowSingleRecordActivity.class);
intent.putExtra("ID", ItemId);
context.startActivity(intent);
}
hopefully this will work .. but what exactly is your problem ? is it detecting the clicked value or passing ID to new Activity?
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
// Get current position of item in RecyclerView to bind data and assign values from list
MyHolder myHolder= (MyHolder) holder;
DataFish current=data.get(position);
myHolder.setTag(current); //<--added
myHolder.company.setText(current.company);
myHolder.name.setText(current.name);
myHolder.family.setText(current.family);
myHolder.id.setText(current.id);
myHolder.id.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));
((MyHolder ) holder).itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
DataFish clickedData = (DataFish) v.getTag(); //<-- pull data from tag
Intent intent = new Intent(context, ShowSingleRecordActivity.class);
intent.putExtra("ID", clickedData.id);
context.startActivity(intent);
}
});
}
Try with following code hope so it will be working.
public class AdapterFish extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private LayoutInflater inflater;
List<DataFish> data= Collections.emptyList();
DataFish current;
int currentPos=0;
public String IDHOLDER;
private Context activity;
// create constructor to initialize context and data sent from MainActivity
public AdapterFish(Context context, List<DataFish> data){
this.context=context;
inflater= LayoutInflater.from(context);
this.data=data;
}
// Inflate the layout when ViewHolder created
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflater.inflate(R.layout.container_fish, parent,false);
MyHolder holder=new MyHolder(view);
return holder;
}
// Bind data
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
// Get current position of item in RecyclerView to bind data and assign values from list
MyHolder myHolder= (MyHolder) holder;
DataFish current=data.get(position);
myHolder.company.setText(current.company);
myHolder.name.setText(current.name);
myHolder.family.setText(current.family);
myHolder.id.setText(current.id);
myHolder.id.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));
((MyHolder ) holder).itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
//final String ItemId = id.getText().toString().trim();
Intent intent = new Intent(context, ShowSingleRecordActivity.class);
intent.putExtra("ID", current.id);
context.startActivity(intent);
}
});
}
// return total item from List
#Override
public int getItemCount() {
return data.size();
}
public Context getActivity() {
return activity;
}
public void setActivity(Context activity) {
this.activity = activity;
}
class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView company;
TextView name;
TextView family;
TextView id;
// create constructor to get widget reference
public MyHolder(View itemView) {
super(itemView);
company= (TextView) itemView.findViewById(R.id.company);
name = (TextView) itemView.findViewById(R.id.name);
family = (TextView) itemView.findViewById(R.id.family);
id = (TextView) itemView.findViewById(R.id.id);
itemView.setOnClickListener(this);
}
// Click event for all items
#Override
public void onClick(View v) {
}
}}
ShowSingleRecordActivity.java (Receiving ID)
public class ShowSingleRecordActivity extends AppCompatActivity {
HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;
// Http Url For Filter Student Data from Id Sent from previous activity.
String HttpURL = "http://192.168.137.1/namayeshgah/FilterStudentData.php";
// Http URL for delete Already Open Student Record.
String HttpUrlDeleteRecord = "http://192.168.137.1/namayeshgah/DeleteStudent.php";
String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
String ParseResult ;
HashMap<String,String> ResultHash = new HashMap<>();
String FinalJSonObject ;
TextView COMPANY,NAME,FAMILY,GENDER,EMAIL1,EMAIL2,PHONE,FAX,TELLFAX,MOBILE;
String CompanyHolder ,NameHolder,FamilyHolder,GenderHolder,Email1Holder,Email2Holder,PhoneHolder,FaxHolder,TellfaxHolder,MobileHolder;
Button UpdateButton, DeleteButton;
String TempItem;
ProgressDialog progressDialog2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_single_record);
COMPANY = (TextView)findViewById(R.id.ncompany);
NAME = (TextView)findViewById(R.id.nname);
FAMILY=(TextView)findViewById(R.id.nfamily);
GENDER =(TextView)findViewById(R.id.ngender);
EMAIL1= (TextView)findViewById(R.id.nemail1);
EMAIL2= (TextView)findViewById(R.id.nemail2);
PHONE= (TextView)findViewById(R.id.nphone);
FAX = (TextView)findViewById(R.id.nfax);
TELLFAX = (TextView)findViewById(R.id.ntellfax);
MOBILE = (TextView)findViewById(R.id.nmobile);
UpdateButton = (Button)findViewById(R.id.buttonUpdate);
DeleteButton = (Button)findViewById(R.id.buttonDelete);
//Receiving the ListView Clicked item value send by previous activity.
TempItem = getIntent().getExtra("ID");
System.out.println("TempItem=============>"+TempItem )
//Calling method to filter Student Record and open selected record.
if(null != TempItem){
HttpWebCall(TempItem);
}else{
Toast.makeText(context, "Item ID is not get from list", Toast.LENGTH_SHORT).show();
}
UpdateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ShowSingleRecordActivity.this,UpdateActivity.class);
// Sending Student Id, Name, Number and Class to next UpdateActivity.
intent.putExtra("Id", TempItem);
intent.putExtra("company",CompanyHolder );
intent.putExtra("name", NameHolder);
intent.putExtra("family",FamilyHolder );
intent.putExtra("gender",GenderHolder );
intent.putExtra("email1",Email1Holder );
intent.putExtra("email2",Email2Holder );
intent.putExtra("phone",PhoneHolder );
intent.putExtra("fax",FaxHolder );
intent.putExtra("tellfax",TellfaxHolder );
intent.putExtra("mobile",MobileHolder );
startActivity(intent);
// Finishing current activity after opening next activity.
finish();
}
});
// Add Click listener on Delete button.
DeleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Calling Student delete method to delete current record using Student ID.
StudentDelete(TempItem);
}
});
}
// Method to Delete Student Record
public void StudentDelete(final String StudentID) {
class StudentDeleteClass extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog2 = ProgressDialog.show(ShowSingleRecordActivity.this, "Loading Data", null, true, true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
progressDialog2.dismiss();
Toast.makeText(ShowSingleRecordActivity.this, httpResponseMsg.toString(), Toast.LENGTH_LONG).show();
finish();
}
#Override
protected String doInBackground(String... params) {
// Sending STUDENT id.
hashMap.put("StudentID", params[0]);
finalResult = httpParse.postRequest(hashMap, HttpUrlDeleteRecord);
return finalResult;
}
}
StudentDeleteClass studentDeleteClass = new StudentDeleteClass();
studentDeleteClass.execute(StudentID);
}
//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem){
class HttpWebCallFunction extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(ShowSingleRecordActivity.this,"Loading Data",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
//Storing Complete JSon Object into String Variable.
FinalJSonObject = httpResponseMsg ;
//Parsing the Stored JSOn String to GetHttpResponse Method.
new GetHttpResponse(ShowSingleRecordActivity.this).execute();
}
#Override
protected String doInBackground(String... params) {
ResultHash.put("StudentID",params[0]);
ParseResult = httpParse.postRequest(ResultHash, HttpURL);
return ParseResult;
}
}
HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();
httpWebCallFunction.execute(PreviousListViewClickedItem);
}
// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
try
{
if(FinalJSonObject != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonObject);
JSONObject jsonObject;
for(int i=0; i<jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
// Storing Student Name, Phone Number, Class into Variables.
CompanyHolder = jsonObject.getString("company");
NameHolder = jsonObject.getString("name");
FamilyHolder= jsonObject.getString("family");
GenderHolder= jsonObject.getString("gender");
Email1Holder = jsonObject.getString("email1");
Email2Holder = jsonObject.getString("email2");
PhoneHolder = jsonObject.getString("phone");
FaxHolder = jsonObject.getString("fax");
TellfaxHolder = jsonObject.getString("tellfax");
MobileHolder = jsonObject.getString("mobile");
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
// Setting Student Name, Phone Number, Class into TextView after done all process .
COMPANY.setText(CompanyHolder);
NAME.setText(NameHolder);
FAMILY.setText(FamilyHolder);
GENDER.setText(GenderHolder);
EMAIL1.setText(Email1Holder);
EMAIL2.setText(Email2Holder);
PHONE.setText(PhoneHolder);
FAX.setText(FaxHolder);
TELLFAX.setText(TellfaxHolder);
MOBILE.setText(MobileHolder);
}
}
Replace this line in ShowSingleRecordActivity
TempItem = getIntent().getStringExtra("ID");
to
TempItem = getIntent().getExtras().getString("ID");

how to show image with json url in android list view

I write program to get data(text) from json and show it in list view , i write the code and its working but now i get url of image with json but i dont know how to show the image in list view with image view,
please help me
here is my code
MainActivity:
public class MainActivity extends ListActivity {
private ProgressDialog pd;
JSONParser jParser=new JSONParser();
ArrayList<HashMap<String,String>> P;
JSONArray s=null;
private final String url="http://192.168.1.4:81/upload/travel.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
P = new ArrayList<>();
new travel().execute();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String id_code=((TextView)v.findViewById(R.id.id_code)).getText().toString();
Intent in=new Intent(MainActivity.this,ADD.class);
in.putExtra("id",id_code);
startActivity(in);
}
class travel extends AsyncTask<String,Void,String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(MainActivity.this);
pd.setMessage("login");
pd.show();
}
#Override
protected String doInBackground(String... params) {
List<NameValuePair> parms=new ArrayList<>();
JSONObject json=jParser.makeHTTPRequest(url,"GET");
try {
int t=json.getInt("t");
if(t==1){
s=json.getJSONArray("travel");
for(int i=0;i<s.length();i++){
JSONObject c=s.getJSONObject(i);
String id=c.getString("id");
String companyname=c.getString("companyname");
String cod=c.getString("cod");
String bign=c.getString("bign");
String stop=c.getString("stop");
String date=c.getString("date");
String time=c.getString("time");
String price=c.getString("price");
String url_image=c.getString("url_image");
HashMap<String,String>map=new HashMap<String,String>();
map.put("id",id);
map.put("companyname",companyname);
map.put("cod",cod);
map.put("bign",bign);
map.put("stop",stop);
map.put("date",date);
map.put("time",time);
map.put("price",price);
map.put("url_image",url_image);
P.add(map);
}
}else {
Toast.makeText(MainActivity.this,"No Data Found",Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pd.dismiss();
runOnUiThread(new Runnable() {
#Override
public void run() {
ListAdapter adapter = new SimpleAdapter(MainActivity.this, P, R.layout.item_list,
new String[]{"url_image","companyname", "cod", "bign", "stop", "date", "time", "price"},
new int[]{R.id.id_code,R.id.companyname, R.id.cod, R.id.bign, R.id.stop, R.id.date, R.id.time1, R.id.price});
setListAdapter(adapter);
}
});
}
}
}
i would suggest you use best library for image loading ASYNC
PICASSO LIBRARY LINK
Now you should write code
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
to show image from url into an ImageView use this class:
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
In order to use it just use this command in your code:
new DownloadImageTask(imageView).execute(imageLinkURL);

RecyclerView didn't updated using notifyDataSetChanged

I'm using RecyclerView to make a list cart. When the cart is cleared the RecyclerView still showing the last list cart. I want the RecyclerView to show nothing when the cart is cleared. I've tried using notifyDataSetChanged() but it didn't work. Please help me.
Tes4Activity.java
final Button buttonDeleteAll = (Button) findViewById(R.id.bClear);
buttonDeleteAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteAllListCart(Tes1Config.KD_MEJA);
getData();
total(Tes1Config.KD_MEJA);
//finish();
//Intent intent = new Intent(Tes4Activity.this, Tes4Activity.class);
//startActivity(intent);
}
});
private void getData(){
class GetData extends AsyncTask<Void,Void,String>{
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(Tes4Activity.this,
"Fetching Data", "Please wait...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
parseJSON(s);
//showData();
total(Tes1Config.KD_MEJA);
}
#Override
protected String doInBackground(Void... params) {
BufferedReader bufferedReader = null;
try {
URL url = new URL(Tes1Config.CART_LIST_URL+Tes1Config.EXTURLZ+Tes1Config.KD_MEJA);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
return sb.toString().trim();
}catch(Exception e){
// Oops
}
return null;
}
}
GetData gd = new GetData();
gd.execute();
}
public void showData(){
// if (Tes1Config.kd_menu == null){
// Toast.makeText(this, "please choose your menu!", Toast.LENGTH_LONG).show();
//}
//else {
adapter = new Tes2Adapter(Tes1Config.kd_menu, Tes1Config.nama, Tes1Config.harga, Tes1Config.jumlah,
Tes1Config.subtotal, Tes1Config.total, Tes1Config.gambar, Tes1Config.gambars);
if(recyclerView.getAdapter() == null){ //Adapter not set yet.
recyclerView.setAdapter(adapter);
}
else {
recyclerView.setAdapter(adapter);
//Already has an adapter
adapter.notifyDataSetChanged();
recyclerView.refreshDrawableState();
}
//recyclerView.setAdapter(adapter);
//adapter.notifyDataSetChanged();
//recyclerView.refreshDrawableState();
}
//}
private void deleteAllListCart(String kd_meja){
class RegisterUser extends AsyncTask<String, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(Tes4Activity.this, "Please Wait",null, true, true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(Tes4Activity.this, s , Toast.LENGTH_LONG).show();
getData();
}
#Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<String,String>();
data.put("kd_meja",params[0]);
RequestHandler rh = new RequestHandler();
String result = rh.sendPostRequest(Tes1Config.CART_DELETE_ALL_URL+Tes1Config.EXTURLZ+Tes1Config.KD_MEJA, data);
return result;
}
}
RegisterUser ru = new RegisterUser();
ru.execute(kd_meja);
}
Tes2Adapter
public class Tes2Adapter extends RecyclerView.Adapter<Tes2Adapter.ViewHolder> {
public List<ListItem2> items;
Context context;
Context mContext;
private EditText editQuantity;
String var_nama;
String var_kdmeja;
String var_kodemenu;
String var_harga;
Tes4Activity tes4Activity;
private RecyclerView.Adapter adapter;
private RecyclerView recyclerView;
private Tes1Config tes1Config;
String total;
public Tes2Adapter(String[] kd_menu,String[] nama,String[] harga,
String[] jumlah,String[] subtotal,String[] total,String[] gambar, Bitmap gambars[]){
super();
//kd_meja = Tes1Config.KD_MEJA;
items = new ArrayList<ListItem2>();
for(int i = 0; i<nama.length; i++){
ListItem2 item = new ListItem2();
item.setKd_menu(kd_menu[i]);
item.setNama(nama[i]);
item.setHarga(harga[i]);
item.setJumlah(jumlah[i]);
item.setSubtotal(subtotal[i]);
item.setTotal(total[i]);
item.setGambar(gambar[i]);
item.setGambars(gambars[i]);
items.add(item);
}
}

Android Spinner selected item not showing

i got the items from the database
Here's the java code
package com.example.androidtablayout;
public class Leave extends Activity implements OnItemSelectedListener{
Button btnSubmitLeave,btnLogout;
SessionManager session;
JSONParser jsonParser = new JSONParser();
Spinner mySpinner;
ProgressDialog mProgressDialog;
JSONArray jsonarray;
ArrayList<String> leavetype;
String username;
EditText inputStart,inputEnd,inputReason;
final Calendar myCalendar = Calendar.getInstance();
private String url_leavetype = "http://10.0.3.2/sunshine-ems/get_leavetype.php";
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.leave);
// CHECK TO LOGIN SESSION
session = new SessionManager(getApplicationContext());
session.checkLogin();
username = session.getUsername();
inputReason = (EditText) findViewById(R.id.inputReason);
inputStart = (EditText) findViewById(R.id.inputStart);
inputEnd = (EditText) findViewById(R.id.inputEnd);
btnSubmitLeave = (Button) findViewById(R.id.btnSubmitLeave);
//spinner
mySpinner= (Spinner) findViewById(R.id.spinnerLeaveType);
leavetype = new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, leavetype);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
new getLeaveTypes().execute();
mySpinner.setAdapter(adapter);
mySpinner.setOnItemSelectedListener(this);
}
private class getLeaveTypes extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(Leave.this);
mProgressDialog.setTitle("Getting Leave types");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... args) {
int success;
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
try {
params1.add(new BasicNameValuePair("username", username));
JSONObject json = jsonParser.makeHttpRequest(url_leavetype, "GET",params1);
// full json response
Log.d("Get Leave types", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
JSONArray type = json.getJSONArray("leavetypes");
for (int i = 0; i < type.length(); i++) {
JSONObject catObj = (JSONObject) type.get(i);
leavetype.add(catObj.optString("leave_name"));
}
} else {
Log.d("Login 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
mProgressDialog.dismiss();
}
}
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(
getApplicationContext(),
parent.getItemAtPosition(position).toString() + " Selected" ,
Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
}
That data from the database is there, the spinner list is showing, but when i clicked an item, it's not showing on that spinner.
I hope someone canhelp me here. Thank you
Add this adapter.notifyDataSetChanged() in onPostExecute() method:
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
adapter.notifyDataSetChanged();
mProgressDialog.dismiss();
}

Categories

Resources