I'm trying to put an extra when calling my intent for the second activity (after logging in) which contains the json data. The json data gets called correctly in the BackgroundTask class in the LoginActivity (I know that, because the Log I put in there with the json string is displayed), but when I do the startChildActivityIntent.putExtra it says that the json_string variable is null (which causes an error in TaskActivity).I hope someone can tell me what's going wrong? I left some comments where things go wrong exactly. Here is the code:
LoginActivity:
package com.example.myApp;
some imports
public class LoginActivity extends AppCompatActivity {
GoogleSignInOptions gso;
GoogleSignInClient mGoogleSignInClient;
SignInButton signInButton;
private int RC_SIGN_IN = 6;
String json_string;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.server_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
#Override
protected void onStart() {
super.onStart();
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
updateUI(account);
}
private void updateUI(GoogleSignInAccount account) {
if(account == null){
signInButton = findViewById(R.id.sign_in_button);
signInButton.setSize(SignInButton.SIZE_WIDE);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signIn();
}
});
signInButton.setVisibility(View.VISIBLE);
} else {
//here the json_string is correct
new BackgroundTask().execute();
Context context = LoginActivity.this;
Class destinationActivity = TaskActivity.class;
Intent startChildActivityIntent = new Intent(context, destinationActivity);
//here the json_string is null again
startChildActivityIntent.putExtra("json_data", json_string);
startActivity(startChildActivityIntent);
}
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
String idToken = account.getIdToken();
updateUI(account);
} catch (ApiException e) {
updateUI(null);
}
}
class BackgroundTask extends AsyncTask<Void, Void, String> {
String json_url;
String JSON_STRING;
#Override
protected void onPreExecute() {
json_url = "https://my_url/json_get_data.php";
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
json_string = result;
//this log is displayed with the json_string filled in correctly
Log.i("onpostexecute","json: " + json_string);
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_STRING = bufferedReader.readLine()) != null){
stringBuilder.append(JSON_STRING + "\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
TaskActivity:
package com.example.myApp;
some imports
public class TaskActivity extends AppCompatActivity {
private static final String URL_DATA = "https://my_url/json_get_data.php";
private RecyclerView recyclerView;
private RecyclerView.Adapter scorpioAdapter;
private List<ListItem> listItems;
String json_string;
JSONObject jsonObject;
JSONArray jsonArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task);
recyclerView = findViewById(R.id.rv);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
loadRecyclerViewData();
}
private void loadRecyclerViewData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading data...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL_DATA,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
json_string = getIntent().getExtras().getString("json_data");
try {
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
int id;
String name, and, some, other, fields;
while (count < jsonObject.length()){
JSONObject o = jsonArray.getJSONObject(count);
id = o.getInt("id");
name = o.getString("name");
and= o.getString("and");
some= o.getInt("some");
other= o.getString("other");
fields= o.getString("fields");
ListItem item = new ListItem(id, name, and, some, other, fields);
listItems.add(item);
}
myAdapter = new myAdapter (listItems, getApplicationContext());
recyclerView.setAdapter(myAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getApplicationContext(), volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
}
);
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
This is because you are calling the background task and without waiting for the result you are passing json_string as an extra. As a result json_string will be null because the background task has not completed execution.
To avoid this, try calling TaskActivity from onPostExecute
#Override
protected void onPostExecute(String result) {
json_string = result;
//this log is displayed with the json_string filled in correctly
Log.i("onpostexecute","json: " + json_string);
Intent startChildActivityIntent = new Intent(LoginActivity.this, TaskActivity.class);
startChildActivityIntent.putExtra("json_data", json_string);
startActivity(startChildActivityIntent);
}
and remove the already existing intent call
Related
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");
I'm trying to add images to my listview, which is made from content retrieved from json. For the purpose of adding the images I'm trying to use picasso, and I've watched a tutorial about it and it worked, the problem is that I don't think it can be used in my app, at least not with the method I saw.
Here's my code, hope anyone can help me and explain me how to do this.
public class TodosOsPaises extends AppCompatActivity {
private String TAG = TodosOsPaises.class.getSimpleName();
private ProgressDialog pDialog;
private ListView lv;
private static String url = "http://";
ArrayList<HashMap<String, String>> listaPaises;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todos_os_paises);
listaPaises = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetPaises().execute();
}
private class GetPaises extends AsyncTask<Void, Void, Void> implements Serializable {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(TodosOsPaises.this);
pDialog.setMessage("Aguarde...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
HttpHandler sh = new HttpHandler();
final String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from URL: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray array = new JSONArray(jsonStr);
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
JSONArray paises = jsonObject.optJSONArray("paises");
if (paises != null) {
for (int j = 0; j < paises.length(); j++) {
JSONObject jsonObject1 = paises.getJSONObject(j);
String K_PAIS = jsonObject1.getString("K_PAIS");
String Designacao = jsonObject1.getString("Designacao");
String URL_IMAGE_SMALL = jsonObject1.getString("URL_IMAGE_SMALL");
String Coord_LAT = jsonObject1.getString("Coord_LAT");
String Coord_LONG = jsonObject1.getString("Coord_LONG");
String Coord_Zoom = jsonObject1.getString("Coord_Zoom");
HashMap<String, String> pais = new HashMap<>();
pais.put("K_PAIS", K_PAIS);
pais.put("Designacao", Designacao);
pais.put("URL_IMAGE_SMALL", URL_IMAGE_SMALL);
pais.put("URL_IMAGEM", URL_IMAGEM);
pais.put("Coord_LAT", Coord_LAT);
pais.put("Coord_LONG", Coord_LONG);
pais.put("Coord_Zoom", Coord_Zoom);
listaPaises.add(pais);
}
}
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Json parsin error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Couldn't get json from server. Check LogCat for possible errpr!", Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing()) {
pDialog.dismiss();
}
ListAdapter adapter = new SimpleAdapter(TodosOsPaises.this, listaPaises, R.layout.list_item, new String[]{"Designacao", "URL_IMAGEM"},
new int[]{R.id.Designacao, R.id.imageViewPais});
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> pare, View view, int position, long id) {
Intent intent = new Intent(TodosOsPaises.this, MapsActivity.class);
intent.putExtra("data", listaPaises.get(position));
startActivity(intent);
}
});
Collections.sort(listaPaises, new Comparator<HashMap<String, String>>() {
#Override
public int compare(HashMap<String, String> first, HashMap<String, String> second) {
String firstValue = first.get("Designacao");
String secondValue = second.get("Designacao");
return firstValue.compareTo(secondValue);
}
});
}
}
}
Picasso.with(content)
.load("path_or_url_or_file")
.into(new Target() {
#Override public void onBitmapLoaded(final Bitmap bitmap,
final Picasso.LoadedFrom from) {
}
#Override public void onBitmapFailed(final Drawable errorDrawable) {
}
#Override public void onPrepareLoad(final Drawable placeHolderDrawable) {
}
});
I'm using firebase-UI to log in with twitter, and now as the docs say I have to get an access token using the method private void handleTwitterSession(TwitterSession session) . The login is working fine but I don't know what to send to that function the so called "Session". How do I get the access token from the FirebaseAuth mAuth object??...Thank you very much. The links to the docs are this https://firebase.google.com/docs/auth/android/twitter-login
public class MainActivity extends AppCompatActivity {
private static final String TAG = "NearGoal";
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private List<causes> causesList = new ArrayList<>();
private List<FundItem> fundItemList = new ArrayList<>();
private RecyclerView rv;
private RecyclerView rvgoal;
private causes_adaptor cAdapter;
private causes_adaptor_near_goal gAdapter;
private ProgressBar pb;
private ProgressBar progressBarGral;
private Context mContext;
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
// already signed in
FirebaseUser firebaseUser=mAuth.getCurrentUser();
Log.d("TWITTER_USER_INFO",""+mAuth.getCurrentUser().getToken(true));
} else {
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setProviders(Arrays.asList(
new AuthUI.IdpConfig.Builder(AuthUI.TWITTER_PROVIDER).build()))
.build(),
RC_SIGN_IN);
}
//TwitterAuthProvider
Fresco.initialize(getApplication());
setContentView(R.layout.activity_main);
rv = (RecyclerView) findViewById(R.id.rv);
rvgoal = (RecyclerView) findViewById(R.id.rvgoal);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
rv.setLayoutManager(mLayoutManager);
rv.setItemAnimator(new DefaultItemAnimator());
RecyclerView.LayoutManager gLayoutManager =new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
rvgoal.setLayoutManager(gLayoutManager);
rvgoal.setDrawingCacheEnabled(true);
rvgoal.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
rvgoal.setItemAnimator(new DefaultItemAnimator());
toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle("Your Title");
//toolbar.setTitleTextColor(getResources().getColor(android.R.color.transparent));
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
//tabLayout = (TabLayout) findViewById(R.id.tabs);
//tabLayout.setupWithViewPager(viewPager);
//collapsingToolbarLayout.setTitle(" ");
pb=(ProgressBar) findViewById(R.id.ProgressBar);
progressBarGral = (ProgressBar) findViewById(R.id.progress_bar);
// String url = "http://10.0.2.2:3000/api/campaigns/get/all//api/campaigns/get/all/";
new DownloadTask().execute();;
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
}
};
}
public class DownloadTask extends AsyncTask<String, Void, Integer> {
URL url = null;
#Override
protected void onPreExecute() {
progressBarGral.setVisibility(View.VISIBLE);
}
#Override
protected Integer doInBackground(String... params) {
Integer result = 0;
HttpURLConnection urlConnection;
try {
url = new URL(getResources().getString(R.string.backend_base_url)+"/api/campaigns/get/all/");
urlConnection = (HttpURLConnection) url.openConnection();
int statusCode = urlConnection.getResponseCode();
// 200 represents HTTP OK
if (statusCode == 200) {
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
parseResult(response.toString());
result = 1; // Successful
} else {
result = 0; //"Failed to fetch data!";
}
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
return result; //"Failed to fetch data!";
}
#Override
protected void onPostExecute(Integer result) {
progressBarGral.setVisibility(View.GONE);
if (result == 1) {
gAdapter = new causes_adaptor_near_goal(MainActivity.this, causesList);
//gAdapter = new causes_adaptor_near_goal(getApplicationContext(), causesList);
rvgoal.setAdapter(gAdapter);
cAdapter = new causes_adaptor(MainActivity.this, causesList);
//gAdapter = new causes_adaptor_near_goal(getApplicationContext(), causesList);
rv.setAdapter(cAdapter);
} else {
Toast.makeText(MainActivity.this, "Failed to fetch data!", Toast.LENGTH_SHORT).show();
}
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.getJSONArray("rows");
causesList = new ArrayList<>();
JSONArray funds;
for (int i = 0; i < posts.length(); i++) {
fundItemList = new ArrayList<>();
JSONObject post = posts.optJSONObject(i);
funds = post.getJSONArray("foundations");
causes item = new causes();
item.setName(post.optString("name"));
item.setcause_description(post.optString("cause_description"));
item.setGoal(post.optString("goal"));
item.setCurrent_contributions(post.optString("current_contributions"));
item.setTotalUniqueUsersReached(post.optString("totalUniqueUsersReached"));
item.setState(post.optString("state"));
item.setId(post.optString("_id"));
item.setRemaining_ammount_to_goal(post.optString("remaining_ammount_to_goal"));
item.setGoal_percentage_achieved(post.optString("goal_percentage_achieved"));
item.setCampaign_ending_date(post.optString("campaign_ending_date"));
for(int k=0, len=funds.length(); k <len;k++) {
FundItem fundItem = new FundItem();
JSONObject fund = funds.optJSONObject(k);
fundItem.setTwitter_account(fund.getString("twitter_account"));
fundItem.setName(fund.getString("name"));
fundItem.setPic_path(fund.getString("pic_path"));
fundItemList.add(fundItem);
}
item.setFundlist(fundItemList);
causesList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_home, menu);
return true;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
// user is signed in!
Log.d("user_status","user signed in!!");
return;
}
// Sign in canceled
if (resultCode == RESULT_CANCELED) {
/* startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setProviders(Arrays.asList(
new AuthUI.IdpConfig.Builder(AuthUI.TWITTER_PROVIDER).build()))
.build(),
RC_SIGN_IN);*/
return;
}
// User is not signed in. Maybe just wait for the user to press
// "sign in" again, or show a message.
}
private void handleTwitterSession(TwitterSession session) {
Log.d(TAG, "handleTwitterSession:" + session);
AuthCredential credential = TwitterAuthProvider.getCredential(
session.getAuthToken().token,
session.getAuthToken().secret);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithCredential", task.getException());
Toast.makeText(getApplicationContext(), "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
You can use setCallBack() to get TwitterSession
mLoginButton.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
Log.d(TAG, "twitterLogin:success" + result);
handleTwitterSession(result.data);
}
#Override
public void failure(TwitterException exception) {
Log.w(TAG, "twitterLogin:failure", exception);
}
});
Take a look at this question also.
I solved it by using the firebase ui onActivityResult parameter data instead of trying to use that handleTwitterSession function, cause firebase-ui already handles that loginWithCredentials so it would be redundant.....Changing the onActivityResult is what makes the difference in this case, I post the working code for future reference:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN && resultCode == RESULT_OK) {
IdpResponse response = IdpResponse.fromResultIntent(data);
//twitter token
response.getIdpToken();
//twitter secret
response.getIdpSecret();
}
}
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);
}
}
I am new to android JSON programming. I want to use set and get function in this program ,but when i used get() for full_name,getting null.
public class LoginActivity extends FragmentActivity {
private EditText userName;
private EditText password;
private TextView forgotPassword;
private TextView backToHome;
private Button login;
private CallbackManager callbackManager;
private ReferanceWapper referanceWapper;
Context context;
String regid;
GoogleCloudMessaging gcm;
String SENDER_ID = "918285686540";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
static final String TAG = "GCM";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Utility.setStatusBarColor(this, R.color.tranparentColor);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/OpenSans_Regular.ttf");
userName = (EditText) findViewById(R.id.userName);
userName.setTypeface(tf);
userName.setFocusable(false);
userName.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View view, MotionEvent paramMotionEvent) {
userName.setFocusableInTouchMode(true);
return false;
}
});
password = (EditText) findViewById(R.id.passwordEText);
password.setTypeface(tf);
password.setFocusable(false);
password.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View paramView, MotionEvent paramMotionEvent) {
password.setFocusableInTouchMode(true);
return false;
}
});
forgotPassword = (TextView) findViewById(R.id.forgotPassword);
forgotPassword.setTypeface(tf);
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),ForgotPasswordActivity.class);
startActivity(intent);
}
});
backToHome = (TextView) findViewById(R.id.fromLogToHome);
backToHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
login = (Button) findViewById(R.id.loginBtn);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doLoginTask();
// Intent intent = new Intent(getApplicationContext(), AfterLoginActivity.class);
// startActivity(intent);
}
});
}
private void doLoginTask() {
String strEmail = userName.getText().toString();
String strPassword = password.getText().toString();
if (strEmail.length() == 0) {
userName.setError("Email Not Valid");
} else if (!Utility.isEmailValid(strEmail.trim())) {
userName.setError("Email Not Valid");
} else if (strPassword.length() == 0) {
password.setError(getString(R.string.password_empty));
} else {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject();
jsonObject.putOpt(Constants.USER_NAME, strEmail);
jsonObject.putOpt(Constants.USER_PASSWORD, strPassword);
jsonObject.putOpt(Constants.DEVICE_TOKEN, "11");
jsonObject.putOpt(Constants.MAC_ADDRESS, "111");
jsonObject.putOpt(Constants.GPS_LATITUDE, "1111");
jsonObject.putOpt(Constants.GPS_LONGITUDE, "11111");
} catch (JSONException e) {
e.printStackTrace();
}
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
CustomJSONObjectRequest jsonObjectRequest = new CustomJSONObjectRequest(Request.Method.POST, Constants.USER_LOGIN_URL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
pDialog.dismiss();
Log.e("LoginPage", "OnResponse =" + response.toString());
getLogin(response);
//LoginBean lb = new LoginBean();
//Toast.makeText(getApplicationContext(),lb.getFull_name()+"Login Successfuly",Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),AfterLoginActivity.class);
startActivity(intent);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Something, wrong please try again",Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
});
jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Log.e("LoginPage", "Url= " + Constants.USER_LOGIN_URL + " PostObject = " + jsonObject.toString());
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
}
private void getLogin(JSONObject response) {
if (response != null){
try {
JSONObject jsonObject = response.getJSONObject("data");
LoginBean loginBean = new LoginBean();
loginBean.setUser_id(jsonObject.getString("user_id"));
loginBean.setFull_name(jsonObject.getString("full_name"));
loginBean.setDisplay_name(jsonObject.getString("display_name"));
loginBean.setUser_image(jsonObject.getString("user_image"));
loginBean.setGender(jsonObject.getString("gender"));
loginBean.setAuthorization_key(jsonObject.getString("authorization_key"));
// signUpArrayList.add(signUpBean);
} catch (JSONException e) {
e.printStackTrace();
}
// dataBean.setSignUp(signUpArrayList);
}
LoginBean loginBean = new LoginBean();
Toast.makeText(getApplicationContext(),"Hello"+loginBean.getFull_name(),Toast.LENGTH_LONG).show();
}
public void onBackPressed() {
finish();
}
}
JSON Input:
"{
""user_name"":""ashish#soms.in"",
""user_password"":""123456"",
""device_token"":""1111"",
""mac_address"":""1111"",
""gps_latitude"":""1111"",
""gps_longitude"":""1111""
}"
Here is JSON Response:
{
""data"": {
""user_id"": ""90"",
""full_name"": ""ashish"",
""display_name"": ""ashish"",
""user_image"": ""images/noimage.png"",
""gender"": ""0"",
""authorization_key"": ""4eef1d65f7b470dbca881fe6452ec11457f54489""
}
}
pls comment line LoginBean loginBean = new LoginBean(); then try .
try this code
private void getLogin(JSONObject response) {
LoginBean loginBean=null;
if (response != null){
try {
loginBean = new LoginBean();
JSONObject jsonObject = response.getJSONObject("data");
loginBean.setUser_id(jsonObject.getString("user_id"));
loginBean.setFull_name(jsonObject.getString("full_name"));
loginBean.setDisplay_name(jsonObject.getString("display_name"));
loginBean.setUser_image(jsonObject.getString("user_image"));
loginBean.setGender(jsonObject.getString("gender"));
loginBean.setAuthorization_key(jsonObject.getString("authorization_key"));
// signUpArrayList.add(signUpBean);
} catch (JSONException e) {
e.printStackTrace();
}
// dataBean.setSignUp(signUpArrayList);
}
Toast.makeText(getApplicationContext(),"Hello"+loginBean.getFull_name(),Toast.LENGTH_LONG).show();
}