Send the values of recycleview settext as intent - java

I have a recycleview in a card layout, the cards have 3 values set with a company array, I'm trying to send those values as an intent. But for some reason everything I try the intent ends up sending null
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int i) {
//companyList= new ArrayList<Company>();
//heres where the textviews get there values set
final Company company = companies.get(i);
viewHolder.textViewHead.setText(company.getCompanyTitle());
viewHolder.textviewDesc.setText(company.getCompanyType());
viewHolder.textViewNumber.setText(company.getCompanyNumber());
viewHolder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
///send these to nodes them attach the officers, get both in nodes and send to myview
companylist = new ArrayList<Company>();
//here are my ateempts try and send the values as intents
Company company1 = companies.get(i);
// view.getContext().startActivity(new Intent(view.getContext(), Nodes.class));
Intent skipintent = new Intent(view.getContext(), Nodes.class);
skipintent.putExtra(KEY_NAME, company.getCompanyTitle());
skipintent.putExtra(KEY_NAME,viewHolder.textViewHead.getText().toString());
skipintent.putExtra(KEY_TYPE, company1.getCompanyType());
skipintent.putExtra(KEY_NUMBER, company1.getCompanyNumber());
// view.getContext().startActivity(skipintent);
Bundle bundle = new Bundle();
bundle.putString("Companyname", company.getCompanyTitle());
bundle.putString(KEY_TYPE, company1.getCompanyType());
bundle.putString(KEY_NUMBER, company1.getCompanyNumber());
// bundle.putParcelableArrayList("Companyselected", companylist);
skipintent.putExtras(bundle);
new RetrieveFeedTask().execute(company1.getCompanyNumber());
}
});
}
And here is my activity where I am trying to receive it
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_nodes);
//Toolbar toolbar = findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
//textViewNodes = (TextView) findViewById(R.id.textViewNodes);
// ArrayList<Company> recList = this.getIntent().getParcelableArrayListExtra("Company");
// companyList= new ArrayList <>();
ArrayList<Officer> officerArrayList = this.getIntent().getParcelableArrayListExtra("Officer");
// ArrayList<Company> companyArrayList = this.getIntent().getParcelableArrayListExtra("Companyselected");
Intent skipintent = getIntent();
Bundle bundle = getIntent().getExtras();
if (null != skipintent) { //Null Checking
Company company = new Company();
String companyTITLE = bundle.getString("Companyname");
String companyNUMBER = skipintent.getStringExtra(company.getCompanyNumber());
String companyTYPE = skipintent.getStringExtra(company.getCompanyType());
company.setCompanyNumber(companyNUMBER);
company.setCompanyTitle(companyTITLE);
company.setCompanyType(companyTYPE);
companyList.add(company);
Log.d("help", "onPostExecute: " + company.getCompanyTitle());
}
Log.d("meme", Arrays.toString(new ArrayList[]{companyList}));
here is the end of retrivefeed, I think I should send the values of the textviews here im not sure how
try {
JSONObject object = new JSONObject(response);
JSONArray itemsAraay = object.getJSONArray("items");
officerList = new ArrayList<Officer>();
Log.d("borkofficer", "onPostExecute: " + itemsAraay.length());
for (int i = 0; i < itemsAraay.length(); i++) {
Officer officer = new Officer();
JSONObject jsonObjectNew = itemsAraay.getJSONObject(i);
String name = jsonObjectNew.optString("name");
String role = jsonObjectNew.optString("officer_role");
String appointed_on = jsonObjectNew.optString("appointed_on");
//JSONArray.put(jsonObjectNew);
officer.setOfficerName(name);
officer.setOfficerRole(role);
officer.setOfficerAppointed(appointed_on);
officerList.add(officer);
Log.d("borkofficer", "onPostExecute: " + officer.getOfficerName());
Log.d("borkofficertitle", "onPostExecute: " + officer.getOfficerRole());
}
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("Officer", officerList);
//Intent skipintent = new Intent(view.getContext(), Nodes.class);
Intent intentofficer = new Intent(context.getApplicationContext(), Nodes.class);
intentofficer.putParcelableArrayListExtra("Officer", officerList);
Intent intentofficer1 = new Intent(context.getApplicationContext(), Nodes.class);
intentofficer1.putExtras(bundle);
// context.startActivity(intentofficer1);
intentofficer.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intentofficer1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.getApplicationContext().startActivity(intentofficer);
} catch (JSONException e) {
e.printStackTrace();
}
update im trying to bundle up the value and send in a intent but its still coming up null in the other activity is it because of the other intent im trying to send?
class RetrieveFeedTask extends AsyncTask {
private Exception exception;
protected String doInBackground(String... numbers) {
companylist = new ArrayList<Company>();
Company company = new Company();
String companynumber = numbers[0];
String companytitle = numbers[1];
String companytype = numbers[2];
company.setCompanyTitle(companytitle);
company.setCompanyType(companytype);
company.setCompanyNumber(companynumber);
companylist.add(company);
Bundle bundle1 = new Bundle();
Intent skipintent = new Intent(context.getApplicationContext(), Nodes.class);
skipintent.putExtra(KEY_NAME, companytitle);
skipintent.putExtra(KEY_NUMBER, companynumber);
skipintent.putExtra(KEY_TYPE, companytype);
skipintent.putParcelableArrayListExtra("Companylist", companylist);
skipintent.putExtras(bundle1);
Log.d("connect", "onPostExecute: " + companytitle.toString());
Log.d("connect", "onPostExecute: " + companytype.toString());
try {
URL url = new URL(API_URL + companynumber +"/officers");
Log.d("connect", "onPostExecute: " + companynumber.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Authorization", "uG5RCz7yWRZNKaMlkQRzUPXY1NpN0SRrb8mKSZ-0");
urlConnection.setReadTimeout(15000);
urlConnection.setConnectTimeout(15000);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
} finally {
urlConnection.disconnect();
}
} catch (Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if (response == null) {
response = "THERE WAS AN ERROR";
}
Log.i("INFO", response);
//does this store?
try {
JSONObject object = new JSONObject(response);
JSONArray itemsAraay = object.getJSONArray("items");
officerList = new ArrayList<Officer>();
Log.d("borkofficer", "onPostExecute: " + itemsAraay.length());
for (int i = 0; i < itemsAraay.length(); i++) {
Officer officer = new Officer();
JSONObject jsonObjectNew = itemsAraay.getJSONObject(i);
String name = jsonObjectNew.optString("name");
String role = jsonObjectNew.optString("officer_role");
String appointed_on = jsonObjectNew.optString("appointed_on");
//JSONArray.put(jsonObjectNew);
officer.setOfficerName(name);
officer.setOfficerRole(role);
officer.setOfficerAppointed(appointed_on);
officerList.add(officer);
Log.d("borkofficer", "onPostExecute: " + officer.getOfficerName());
Log.d("borkofficertitle", "onPostExecute: " + officer.getOfficerRole());
}
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("Officer", officerList);
//skipintent.putExtra(KEY_NUMBER, company1.getCompanyNumber());
// view.getContext().startActivity(skipintent);
//Bundle bundle = new Bundle();
// bundle.putString(KEY_NAME,);
//bundle.putString(KEY_TYPE, companylist.get(1).getCompanyType());
//bundle.putString(KEY_NUMBER, companylist.get(1).getCompanyNumber());
//company1.setCompanyTitle(;
//company1.setCompanyNumber(KEY_NUMBER);
// company1.setCompanyType(KEY_TYPE);
// companylist.add(company1);
// bundle.putParcelableArrayList("Companyselected", companylist);
//skipintent.putExtras(bundle);
Intent intentofficer = new Intent(context.getApplicationContext(), Nodes.class);
intentofficer.putParcelableArrayListExtra("Officer", officerList);
Intent intentofficer1 = new Intent(context.getApplicationContext(), Nodes.class);
intentofficer1.putExtras(bundle);
// context.startActivity(intentofficer1);
intentofficer.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intentofficer1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.getApplicationContext().startActivity(intentofficer);

Inside the activity, try to extract values with same keys as were used in adapter. Use
String companyNUMBER = skipintent.getStringExtra(KEY_NUMBER);
String companyTYPE = skipintent.getStringExtra(KEY_TYPE);
instead of
String companyNUMBER = skipintent.getStringExtra(company.getCompanyNumber());
String companyTYPE = skipintent.getStringExtra(company.getCompanyType());
UPDATE
To start activity inside the AsyncTask, pass data as a constructor parameter: new RetrieveFeedTask(company.getCompanyName()).
private String mCompanyName;
RetrieveFeedTask(String companyName) {
this.mCompanyName = companyName;
}
and then use it as usually to put in the intent:
intent.putExtra(KEY_NAME, mCompanyName);
UPDATE 2
As an alternative, you can pass data in the new RetrieveFeedTask().execute(company1.getCompanyNumber(), company1.getCompanyTitle(), company1.getCompanyType()) method and use them in doInBackground:
String doInBackground(String... data) {
String companyNumber = data[0];
String companyTitle = data[1];
String companyType = data[2];
// ...
}

Related

HttpURLConnection won't work after pausing on activity

I have an Activity that uses a ListView to display an array of data fetched from a JSON response. Clicking on one of the items will present the user with a business card activity, displaying the data associated with the item clicked. When the application first loads, it works fine. I can close the business card and reopen it multiple times. However, if i pause on the ListView activity, the page will no longer load the data. I have placed Log.d commands before and after the connection to try debugging the issue. The activity is receiving the information necessary to perform the connection. However, the closest I have gotten to a solution is knowing that when it doesn't work, I cannot Log.d the response code immediately after opening the connection.
To be clear, I am including the entirety of the code I am using, just in case the issue lies somewhere else. First is the code for the ListView Activity, then is the Business Card Activity code.
This is the Directory Activity.
public class DirectoryActivity extends AppCompatActivity {
ListView lvContacts;
Button goMenu;
Button goFilter;
TextView tempText;
static ArrayList<String> arrlst = new ArrayList<>();
static ArrayAdapter<String> adapter;
private FetchList process;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_directory);
lvContacts = findViewById(R.id.lvContacts);
goMenu = findViewById(R.id.btn_goMenu);
goFilter = findViewById(R.id.btn_goSearch);
tempText = findViewById(R.id.temptext);
// Set adapter for listview: used in FetchList
adapter = new ArrayAdapter<>(this, R.layout.layout_org_list, R.id.listViewItem, arrlst );
lvContacts.setAdapter(adapter);
// Get list from DB
process = new FetchList();
process.setListener(new FetchList.FetchListTaskListener() {
#Override
public void onFetchListTaskFinished(String[] result) {
// update UI in Activity here
arrlst.clear();
for (String OrgName:result) {
addItemsToList(OrgName);
}
adapter.notifyDataSetChanged();
}
});
process.execute();
// Set onclick listener for listview
lvContacts.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
String selectedOrg = lvContacts.getItemAtPosition(position).toString(); // Get org name from list view
goBusinessCard(selectedOrg); // Go to business card
}
});
}
#Override
protected void onDestroy() {
process.setListener(null); // PREVENT LEAK AFTER ACTIVITY DESTROYED
super.onDestroy();
}
public static void addItemsToList(String item) {
arrlst.add(item);
}
// Set Methods for Buttons
public void goMenu(View v) {
startActivity(new Intent(this, HomeActivity.class));
}
public void goFilter(View v) {
startActivity(new Intent(this, FilterActivity.class));
Log.d("FILTER DEBUG", "checking if extras are filled " + this.getIntent().getExtras());
}
// Method for opening BusinessCardActivity and passes orgID
public void goBusinessCard(String selectedOrg) {
Bundle extras = new Bundle();
extras.clear();
extras.putString("selectedOrg", selectedOrg);
Intent BusinessCard = new Intent(this, BusinessCardActivity.class);
BusinessCard.putExtras(extras);
startActivity(BusinessCard);
}
// ASYNC TASK
static class FetchList extends AsyncTask<Void, Void, String[]> {
private FetchListTaskListener listener;
#Override
protected String[] doInBackground(Void... voids) {
try {
URL url = new URL(URL_READ_ORG ); // Set url to API Call location
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); // Open connection to html
InputStream inputStream = httpURLConnection.getInputStream(); // create input stream from html location
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8")); // create reader for inputStream
StringBuilder data = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null ) {
data.append(line); // creates string from all lines in response
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
JSONObject JO = new JSONObject(data.toString()); // creates object from json response in data string
JSONArray JA = JO.getJSONArray("orgs");
// Create array list to store items from json response
List<String> al_orgList = new ArrayList<>();
// Iterate through JSON array to get json object org_name
for (int i = 0; i < JA.length(); i++) {
JSONObject Orgs = JA.getJSONObject(i);
String org_name = Orgs.getString("org_name");
al_orgList.add(org_name);
}
// convert array list to array
return al_orgList.toArray(new String[al_orgList.size()]);
} catch (JSONException | IOException e) {
e.printStackTrace();
}
return null;
}
// UI Process - allows manipulation of UI
#Override
protected void onPostExecute(String[] result) {
super.onPostExecute(result);
if (listener != null) {
listener.onFetchListTaskFinished(result);
}
}
private void setListener(FetchListTaskListener listener) {
this.listener = listener;
}
public interface FetchListTaskListener {
void onFetchListTaskFinished(String[] result);
}
}
This is the Business Card Activity that runs the data fetch for individual items
public class BusinessCardActivity extends AppCompatActivity {
TextView tv_org, tv_name, tv_email, tv_phone, tv_website, tv_servicetype,
tv_servicesprovided, tv_address;
String Favorite, Latitude, Longitude, selectedOrg, FavoriteChanged, dbPhone, phoneNum, dbWeb, orgWeb;
CheckBox cbFavorite;
List<String> arrlstID = new ArrayList<>();
String[] arrID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business_card);
// Assign fields to variables
tv_org = findViewById(R.id.tv_org);
tv_name = findViewById(R.id.tv_name);
tv_email = findViewById(R.id.tv_email);
tv_phone = findViewById(R.id.tv_phone);
tv_website = findViewById(R.id.tv_website);
tv_servicetype = findViewById(R.id.tv_servicetype);
tv_servicesprovided = findViewById(R.id.tv_servicesprovided);
tv_address = findViewById(R.id.tv_address);
cbFavorite = findViewById(R.id.cbFavorite);
// Set variable for selectedOrg from DirectoryActivity
selectedOrg = Objects.requireNonNull(this.getIntent().getExtras()).getString("selectedOrg");
// Get Org data from DB using async
process = new FetchOrg();
process.setListener(new FetchOrg.FetchOrgTaskListener() {
#Override
public void onFetchOrgTaskFinished(String[] result) {
setTextView(result);
// onClick for Email
tv_email.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
showEmailDialog();
}
});
// onClick for Call
tv_phone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Get phone number from DB
// Replace any non-digit in phone number to make call
phoneNum = dbPhone.replaceAll("\\D", "");
// make call
goCall(phoneNum);
}
});
// onClick for Web
tv_website.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Fix URL logic
orgWeb = "http://" + dbWeb;
goWeb(orgWeb);
}
});
// onClick for Address
tv_address.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goMap();
}
});
// TODO add favorite functionality
// When checkbox status changes, change value of Favorite
cbFavorite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
}
});
process.execute(selectedOrg);
/*
// if favorite = 1 then check box
if (Favorite.equals("1")) {
cbFavorite.setChecked(true);
} else {
cbFavorite.setChecked(false);
}
*/
}
#Override
protected void onDestroy() {
process.setListener(null); // PREVENT LEAK AFTER ACTIVITY DESTROYED
super.onDestroy();
}
// Method to assign text view items from async task
public void setTextView(String[] org_data) {
String name = org_data[1] + " " + org_data[2];
String address = org_data[8] + " " + org_data[9] + " " + org_data[10] + " " + org_data[11];
tv_org.setText(org_data[0]);
tv_name.setText(name);
tv_email.setText(org_data[3]);
tv_phone.setText(org_data[4]);
tv_website.setText(org_data[5]);
tv_servicetype.setText(org_data[6]);
tv_servicesprovided.setText(org_data[7]);
tv_address.setText(address);
}
public void showEmailDialog() {
// Get dialog_box_goals.xml view
LayoutInflater layoutInflater = LayoutInflater.from(BusinessCardActivity.this);
View promptView = layoutInflater.inflate(R.layout.dialog_box_send_email, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(BusinessCardActivity.this);
alertDialogBuilder.setView(promptView);
final EditText etEmailMessage = (EditText) promptView.findViewById(R.id.etMailMessage);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// my code
/* WONT USE THIS UNTIL EMAILS ARE FINAL
USING MY EMAIL FOR TESTING PURPOSES
// Get email
niagaraDB.open();
c2 = niagaraDB.getEmailByID(passedID);
if (c2.moveToFirst())
{
public String emailTo = c2.getString(0);
}
niagaraDB.close();
*/
// This is for final code
// String to = "mailto:" + emailTo;
String to = "snownwakendirt#yahoo.com";
String subject = "Mail From Connect & Protect Niagara App";
String message = etEmailMessage.getText().toString();
if (message.isEmpty()) {
Toast.makeText(BusinessCardActivity.this,
"Message must contain something",
Toast.LENGTH_LONG).show();
} else {
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[] { to });
// email.putExtra(Intent.EXTRA_CC, new String[]{ to});
// email.putExtra(Intent.EXTRA_BCC, new String[]{to});
email.putExtra(Intent.EXTRA_SUBJECT, subject);
email.putExtra(Intent.EXTRA_TEXT, message);
// need this to prompt email client only
email.setType("message/rfc822");
try {
startActivity(Intent.createChooser(email, "Choose an Email client :"));
finish();
Log.i("Email Sent...", "");
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(BusinessCardActivity.this,
"There is no email client installed.",
Toast.LENGTH_SHORT).show();
}
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
public void goCall(final String phoneNum) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", phoneNum, null)));
}
public void goWeb(String orgWeb) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(orgWeb)));
}
public void goCloseBusinessCard(View v) {
finish();
startActivity(new Intent(this, DirectoryActivity.class));
}
public void goMap() {
/*
int locationAddressLatInt = Integer.parseInt(locationAddressLat);
int locationAddressLongInt = Integer.parseInt(locationAddressLong);
*/
// pass id to map view. only one item in array for ease of use in MapActivity
arrlstID.add(selectedOrg);
arrID = new String[arrlstID.size()];
arrlstID.toArray(arrID);
Bundle extras = new Bundle();
extras.putStringArray("arrID", arrID);
Intent Map = new Intent(BusinessCardActivity.this, MapActivity.class);
Map.putExtras(extras);
startActivity(Map);
}
// ASYNC TASK
static class FetchOrg extends AsyncTask<String, Void, String[]> {
private FetchOrgTaskListener listener;
#Override
protected String[] doInBackground(String... params) {
try {
// assign passed string from main thread
String org_name = params[0];
String orgbyname = URL_GET_ORG_BY_NAME + "?org_name=" + org_name;
String line = "";
URL url = new URL(orgbyname);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
line = br.readLine();
br.close();
is.close();
conn.disconnect();
/*
This JSON section contains a JSON Object that holds a JSON Array. The Array is created to
individualize each object within the JSON Array. Then, each JSON object is fetched and
assigned to a string variable.
*/
JSONObject JO = new JSONObject(line); // creates object from json response in data string
JSONObject Orgs = JO.getJSONObject("orgs"); // creates array for parsing of json data
// get items from JSONArray and assign for passing to onProgressUpdate
String Org = Orgs.getString("org_name");
String FirstName = Orgs.getString("contact_first_name");
String LastName = Orgs.getString("contact_last_name");
String Email = Orgs.getString("contact_email");
String Phone = Orgs.getString("contact_phone");
String Website = Orgs.getString("org_website");
String ServiceType = Orgs.getString("org_type");
String ServicesProvided = Orgs.getString("org_services");
String Address = Orgs.getString("org_street_address");
String City = Orgs.getString("org_city");
String State = Orgs.getString("org_state");
String Zip = Orgs.getString("org_zip");
String Lat = Orgs.getString("latitude");
String Long = Orgs.getString("longitude");
// Add items to string array
String[] org_data = new String[14]; // 14 is length of array, not the count
org_data[0] = Org;
org_data[1] = FirstName;
org_data[2] = LastName;
org_data[3] = Email;
org_data[4] = Phone;
org_data[5] = Website;
org_data[6] = ServiceType;
org_data[7] = ServicesProvided;
org_data[8] = Address;
org_data[9] = City;
org_data[10] = State;
org_data[11] = Zip;
org_data[12] = Lat;
org_data[13] = Long;
return org_data;
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] result) {
super.onPostExecute(result);
if (listener != null) {
listener.onFetchOrgTaskFinished(result);
}
}
private void setListener(FetchOrgTaskListener listener) {
this.listener = listener;
}
public interface FetchOrgTaskListener {
void onFetchOrgTaskFinished(String[] result);
}
}
Activity lifecycle would go back from paused to resume state.
You need to provide the expected behaviour inside onResume something like below
public void onResume(){
super.onResume();
new XXXAsyncTask( new XXXAsyncListener(){
public void postTaskMethod(){
//do stuff here
}
}).execute();
}
I made a few changes in your onCreate()method of your BusinessCardActivity. I check for hasExtra instead--a little more flexibility. I got rid of the Listener and packed all onClick listener below. I felt it was a bit too complicated using the Listener approach (So you can remove this process.setListener(null); from the onDestroy()method). I also added a few Log.e(); so you can see what is going on in the logcat.
(BTW "TAG" would be:
private static final Strting TAG = BusinessCardActivity.class.getSimpleName();)
With "BusinessCardActivity.class.getSimpleName();" written out just in case you refactor sometime.
This is part of your BusinessCardActivity onCreate() method:
// Set variable for selectedOrg from DirectoryActivity
Intent intent = this.getIntent();
if(intent.hasExtra(selectedOrg)){
String selectedOrg = intent.getStringExtra("selectedOrg")
Log.e(TAG, "selectedOrg : " + selectedOrg);
FetchOrg process = new FetchOrg();
process.execute(selectedOrg);
}
else{
Log.e(TAG, "No Extras!")
//You might what to call finish() here
return;
}
//Move all your onClick Listeners below...
I don't think this is the best case to use a Listener so lets use the AsyncTask like this (I also removed the static):
class FetchOrg extends AsyncTask<String, Void, String[]> {
#Override
protected String[] doInBackground(String... params) {
try {
Log.e(TAG, "doInBackground ... Started");
// assign passed string from main thread
String org_name = params[0];
String orgbyname = URL_GET_ORG_BY_NAME + "?org_name=" + org_name;
String line = "";
URL url = new URL(orgbyname);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
line = br.readLine();
br.close();
is.close();
conn.disconnect();
Log.e(TAG, "Data Returned : " + line);
/*
This JSON section contains a JSON Object that holds a JSON Array. The Array is created to
individualize each object within the JSON Array. Then, each JSON object is fetched and
assigned to a string variable.
*/
JSONObject JO = new JSONObject(line); // creates object from json response in data string
JSONObject Orgs = JO.getJSONObject("orgs"); // creates array for parsing of json data
// get items from JSONArray and assign for passing to onProgressUpdate
String Org = Orgs.getString("org_name");
String FirstName = Orgs.getString("contact_first_name");
String LastName = Orgs.getString("contact_last_name");
String Email = Orgs.getString("contact_email");
String Phone = Orgs.getString("contact_phone");
String Website = Orgs.getString("org_website");
String ServiceType = Orgs.getString("org_type");
String ServicesProvided = Orgs.getString("org_services");
String Address = Orgs.getString("org_street_address");
String City = Orgs.getString("org_city");
String State = Orgs.getString("org_state");
String Zip = Orgs.getString("org_zip");
String Lat = Orgs.getString("latitude");
String Long = Orgs.getString("longitude");
// Add items to string array
String[] org_data = new String[14]; // 14 is length of array, not the count
org_data[0] = Org;
org_data[1] = FirstName;
org_data[2] = LastName;
org_data[3] = Email;
org_data[4] = Phone;
org_data[5] = Website;
org_data[6] = ServiceType;
org_data[7] = ServicesProvided;
org_data[8] = Address;
org_data[9] = City;
org_data[10] = State;
org_data[11] = Zip;
org_data[12] = Lat;
org_data[13] = Long;
return org_data;
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] result) {
setTextView(result);
}
}
Also I would change your method goBusinessCard() a bit (and no need to be public):
private void goBusinessCard(String selectedOrg) {
//Java variables should written in lower case and Classes Capitalized
Intent businessCard = new Intent(this, BusinessCardActivity.class);
businessCard.putExtra("selectedOrg", selectedOrg);
startActivity(businessCard);
}
Please let me know if you have any issues! I typed this out in a standard Text Editor..so there might be a few typos.
Posting a new answer so I can add all the code for the BusinessCardActivity class.
I added some additional logging and changed getString() to optString() in order to be able to offer an alternative value. For example if the value or "key" is invalid or missing you would get an error.
public class BusinessCardActivity extends AppCompatActivity {
TextView tv_org, tv_name, tv_email, tv_phone, tv_website, tv_servicetype,
tv_servicesprovided, tv_address;
String Favorite, Latitude, Longitude, FavoriteChanged, dbPhone, phoneNum, dbWeb, orgWeb;
CheckBox cbFavorite;
List<String> arrlstID = new ArrayList<>();
String[] arrID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_business_card);
// Assign fields to variables
tv_org = findViewById(R.id.tv_org);
tv_name = findViewById(R.id.tv_name);
tv_email = findViewById(R.id.tv_email);
tv_phone = findViewById(R.id.tv_phone);
tv_website = findViewById(R.id.tv_website);
tv_servicetype = findViewById(R.id.tv_servicetype);
tv_servicesprovided = findViewById(R.id.tv_servicesprovided);
tv_address = findViewById(R.id.tv_address);
cbFavorite = findViewById(R.id.cbFavorite);
Intent intent = this.getIntent();
if(!intent.hasExtra("selectedOrg")){
Log.e(TAG, "No Extras!")
//You might what to call finish() here
return;
}
String selectedOrg = intent.getStringExtra("selectedOrg")
Log.e(TAG, "selectedOrg : " + selectedOrg);
FetchOrg process = new FetchOrg();
process.execute(selectedOrg);
// onClick for Email
tv_email.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
showEmailDialog();
}
});
// onClick for Call
tv_phone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Get phone number from DB
// Replace any non-digit in phone number to make call
phoneNum = dbPhone.replaceAll("\\D", "");
// make call
goCall(phoneNum);
}
});
// onClick for Web
tv_website.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Fix URL logic
orgWeb = "http://" + dbWeb;
goWeb(orgWeb);
}
});
// onClick for Address
tv_address.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goMap();
}
});
// TODO add favorite functionality
// When checkbox status changes, change value of Favorite
cbFavorite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
}
});
/*
// if favorite = 1 then check box
if (Favorite.equals("1")) {
cbFavorite.setChecked(true);
} else {
cbFavorite.setChecked(false);
}
*/
}
#Override
protected void onDestroy() {
process.setListener(null); // PREVENT LEAK AFTER ACTIVITY DESTROYED
super.onDestroy();
}
// Method to assign text view items from async task
public void setTextView(String[] org_data) {
String name = org_data[1] + " " + org_data[2];
String address = org_data[8] + " " + org_data[9] + " " + org_data[10] + " " + org_data[11];
tv_org.setText(org_data[0]);
tv_name.setText(name);
tv_email.setText(org_data[3]);
tv_phone.setText(org_data[4]);
tv_website.setText(org_data[5]);
tv_servicetype.setText(org_data[6]);
tv_servicesprovided.setText(org_data[7]);
tv_address.setText(address);
}
public void showEmailDialog() {
// Get dialog_box_goals.xml view
LayoutInflater layoutInflater = LayoutInflater.from(BusinessCardActivity.this);
View promptView = layoutInflater.inflate(R.layout.dialog_box_send_email, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(BusinessCardActivity.this);
alertDialogBuilder.setView(promptView);
final EditText etEmailMessage = (EditText) promptView.findViewById(R.id.etMailMessage);
// setup a dialog window
alertDialogBuilder.setCancelable(false)
.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// my code
/* WONT USE THIS UNTIL EMAILS ARE FINAL
USING MY EMAIL FOR TESTING PURPOSES
// Get email
niagaraDB.open();
c2 = niagaraDB.getEmailByID(passedID);
if (c2.moveToFirst())
{
public String emailTo = c2.getString(0);
}
niagaraDB.close();
*/
// This is for final code
// String to = "mailto:" + emailTo;
String to = "snownwakendirt#yahoo.com";
String subject = "Mail From Connect & Protect Niagara App";
String message = etEmailMessage.getText().toString();
if (message.isEmpty()) {
Toast.makeText(BusinessCardActivity.this,
"Message must contain something",
Toast.LENGTH_LONG).show();
} else {
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_EMAIL, new String[] { to });
// email.putExtra(Intent.EXTRA_CC, new String[]{ to});
// email.putExtra(Intent.EXTRA_BCC, new String[]{to});
email.putExtra(Intent.EXTRA_SUBJECT, subject);
email.putExtra(Intent.EXTRA_TEXT, message);
// need this to prompt email client only
email.setType("message/rfc822");
try {
startActivity(Intent.createChooser(email, "Choose an Email client :"));
finish();
Log.i("Email Sent...", "");
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(BusinessCardActivity.this,
"There is no email client installed.",
Toast.LENGTH_SHORT).show();
}
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
public void goCall(final String phoneNum) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", phoneNum, null)));
}
public void goWeb(String orgWeb) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(orgWeb)));
}
public void goCloseBusinessCard(View v) {
finish();
startActivity(new Intent(this, DirectoryActivity.class));
}
public void goMap() {
/*
int locationAddressLatInt = Integer.parseInt(locationAddressLat);
int locationAddressLongInt = Integer.parseInt(locationAddressLong);
*/
// pass id to map view. only one item in array for ease of use in MapActivity
arrlstID.add(selectedOrg);
arrID = new String[arrlstID.size()];
arrlstID.toArray(arrID);
Bundle extras = new Bundle();
extras.putStringArray("arrID", arrID);
Intent Map = new Intent(BusinessCardActivity.this, MapActivity.class);
Map.putExtras(extras);
startActivity(Map);
}
// ASYNC TASK
class FetchOrg extends AsyncTask<String, Void, String[]> {
#Override
protected String[] doInBackground(String... params) {
HttpURLConnection con = null;
String[] org_data = null;
try {
Log.e(TAG, "FetchOrg doInBackground started");
// assign passed string from main thread
String org_name = params[0];
String orgbyname = URL_GET_ORG_BY_NAME + "?org_name=" + org_name;
URL url = new URL(orgbyname);
con = (HttpURLConnection) url.openConnection();
Log.e(TAG, "FetchOrg doInBackground Connected!");
//Check the response code of the server -
Integer replyCode = con.getResponseCode();
logMess += " Reply Code: " + replyCode.toString();
responseStream = new BufferedInputStream(con.getInputStream());
BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
stopTime = System.currentTimeMillis();
elapsedTime = stopTime - startTime;
logMess += " elapsed Time : " + elapsedTime + " ms";
Log.e(TAG, "FetchOrg logMess: --- " + logMess);
String line = "";
StringBuilder stringBuilder = new StringBuilder();
//Make sure you get everything!
while ((line = responseStreamReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
//this will close underlying streams
responseStreamReader.close();
String data = stringBuilder.toString();
Log.e(TAG, "FetchOrg Data: --- " + data);
/*
This JSON section contains a JSON Object that holds a JSON Array. The Array is created to
individualize each object within the JSON Array. Then, each JSON object is fetched and
assigned to a string variable.
*/
JSONObject obj = new JSONObject(data); // creates object from json response in data string
JSONObject orgs = obj.getJSONObject("orgs"); // creates array for parsing of json data
String nA = "not available";
// get items from JSONArray and assign for passing to onProgressUpdate
String Org = orgs.optString("org_name", nA);
String FirstName = orgs.optString("contact_first_name", nA);
String LastName = orgs.optString("contact_last_name", nA);
String Email = orgs.optString("contact_email", nA);
String Phone = orgs.optString("contact_phone", nA);
String Website = orgs.optString("org_website", nA);
String ServiceType = orgs.optString("org_type", nA);
String ServicesProvided = orgs.optString("org_services", nA);
String Address = orgs.optString("org_street_address", nA);
String City = orgs.optString("org_city", nA);
String State = orgs.optString("org_state", nA);
String Zip = orgs.optString("org_zip", nA);
String Lat = orgs.optString("latitude", nA);
String Long = orgs.optString("longitude", nA);
// Add items to string array
org_data = new String[14]; // 14 is length of array, not the count
org_data[0] = Org;
org_data[1] = FirstName;
org_data[2] = LastName;
org_data[3] = Email;
org_data[4] = Phone;
org_data[5] = Website;
org_data[6] = ServiceType;
org_data[7] = ServicesProvided;
org_data[8] = Address;
org_data[9] = City;
org_data[10] = State;
org_data[11] = Zip;
org_data[12] = Lat;
org_data[13] = Long;
} catch (Exception ex) {
Log.e(TAG, "FetchOrg doInBackground: " + ex.getMessage());
}
finally{
//just in case you get an error above
if(con != null){
con.disconnect();
}
}
return org_data;
}
#Override
protected void onPostExecute(String[] result) {
if(result != null){
setTextView(result);
}
else{
Log.e(TAG, "FetchOrg onPostExecute: result is null");
}
}
}
Be aware that I did not clean up things like maintaining minimal scope: For example :public void showEmailDialog() and public void goMap() which do not need to be public methods! Any method that does not need to be accessed outside the class (and that is rare!) should not be made public.
You have also defined many class variables at the beginning of the class like "Favorite, Latitude, Longitude, FavoriteChanged" do they need to have class wide scope?? And they are variables! So in java naming convention, variables and methods are written in lower case, while classes are capitalized--this helps reading code easier (for the SO community!)
When working with Indent extras often mistakes are made when entering the "key" like "selectedOrg". Therefore it is some times an advantage to create a global class to help keep things straight. Example public class GlobalExtras and just keep public static final String SELECTED_ORG = "selectedOrg"; Then just use intent.getString(SELECTED_ORG);
Another thing: I am not a big fan of String[] as you have used to store your "org" strings. They can be tricky with size and indexes. You might want to consider using another object.
I do not have access to your API and your data, so I was only able to make requests on my server trying to duplicate your user scenario, but I was unable to reproduce your issue. I hope this helps, let me know what the logcat spits out!

cant set text in postExecute ,Async, Android

I am not able to find any appropriate solution for below issue. I am using AsyncTask app sends request to server and it returns the JSON array as response, in postExecute method I parsed it, and problem is when I try to set the parsed data to TextView, textview not showing data. I am sure that server returned some data, and this data was parsed in postExecute and saved in global variables. TextViews also was declared as global variables, and defined in OnCreate method. thanks in advance!
Please check Code mentioned below:
public class CompanyData extends AppCompatActivity implements View.OnClickListener {
Button cComments;
String ssid,bin;
String extra, extra1;
TextView compData1, compData2, compData3, compData4, compData5, compData6, compTitle;
String title, kod_okpo, address, reg_date, fio, kod_oked, ovd ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_company_data);
cComments = (Button) findViewById(R.id.cComment);
cComments.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
extra = extras.getString("bin");
extra1 = extras.getString("ssid");
send_company_req(extra1, extra);
}
compTitle = (TextView) findViewById(R.id.companyTitle);
compData1 = (TextView) findViewById(R.id.compData1);
compData2 = (TextView) findViewById(R.id.compData2);
compData3 = (TextView) findViewById(R.id.compData3);
compData4 = (TextView) findViewById(R.id.compData4);
compData5 = (TextView) findViewById(R.id.compData5);
compData6 = (TextView) findViewById(R.id.compData6);
//Toast.makeText(this,"LOOOL" + title+bin+kod_okpo+address+reg_date+fio+kod_oked+ovd, Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.cComment:
Intent companyData = new Intent(CompanyData.this, Comments.class);
companyData.putExtra("bin", bin);
companyData.putExtra("ssid", ssid);
startActivity(companyData);
startActivity(new Intent(this, Comments.class));
break;
}
}
private void send_company_req(final String ssid, final String searchData) {
class GetJSON extends AsyncTask<String, String, String> {
ProgressDialog loading;
String rStr;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(CompanyData.this, "Request...", null, true, true);
}
#Override
protected String doInBackground(String... params) {
String token = params[0];
String fi = params[1];
String uri = Quickstart.URL + "/car/info";
String param = null;
try {
param = "ssid=" + URLEncoder.encode(token, "UTF-8") +
"&bin=" + URLEncoder.encode(fi, "UTF-8") + "&dev=android";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setFixedLengthStreamingMode(param.getBytes().length);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Authorization", "Bearer " + token);
PrintWriter out = new PrintWriter(con.getOutputStream());
out.print(param);
out.close();
String response = "";
Scanner inStream = new Scanner(con.getInputStream());
while (inStream.hasNextLine()) {
response += (inStream.nextLine());
}
return response;
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
//Toast.makeText(CompanyData.this, s, Toast.LENGTH_LONG).show();
JSONArray jsonArrayComp;
try {
jsonArrayComp = new JSONArray(s.trim());
JSONObject jsonObjectComp = jsonArrayComp.getJSONObject(0);
try {
title = jsonObjectComp.getString("title");
kod_okpo = jsonObjectComp.getString("kod_okpo");
address = jsonObjectComp.getString("address");
reg_date = jsonObjectComp.getString("reg_date");
fio = jsonObjectComp.getString("fio");
kod_oked = jsonObjectComp.getString("kod_1_oked");
ovd = jsonObjectComp.getString("vidd");
Toast.makeText(CompanyData.this,"LOOOL" + title+bin+kod_okpo+address+reg_date+fio+kod_oked+ovd, Toast.LENGTH_LONG).show();
} catch (Exception ee) {
}
} catch (Exception e) {
//Toast.makeText(CompanyData.this, "Упс,:( что то пошло не так, попробуйте еще раз пожалуйста.", Toast.LENGTH_SHORT).show();
}
compTitle.setText(title);
compData1.setText(bin);
compData2.setText(kod_okpo);
compData3.setText(address);
compData4.setText(reg_date);
compData5.setText(fio);
compData6.setText(kod_oked + " - " + ovd);
}
}
GetJSON gj = new GetJSON();
gj.execute(ssid, searchData);
}
}

Fetch sms From phone and upload on server

Here i am fetch sms from phone and upload 10 sms on server all code working fine but instead of 10 sms upload to server only Specific one sms uploaded 10 time to server, pls tell me what i am missing in my code?
here is my message_class.Java code.
public class message_class extends Activity{
int j = 0;
Button btninbox;
ListView lstView;
SimpleCursorAdapter adapter;
ArrayList<Message_Item> msg_list;
String Str_Msg, Str_Phone,dated;
Msg_adapter msg_adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.msginbox_layout);
msg_list = new ArrayList<Message_Item>();
btninbox = (Button) findViewById(R.id.btn_inbox);
btninbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(message_class.this, Msg_Recive.class);
startActivity(intent);
}
});
lstView = (ListView) findViewById(R.id.lv_msg);
fetchInbox();
final int arraysize = msg_list.size();
for (int j=0; j<10;j++){
Str_Msg = msg_list.get(j).getStrMsg().toString();
Str_Phone = msg_list.get(j).getStrNumber().toString();
Toast.makeText(message_class.this, Str_Phone+" "+Str_Msg, Toast.LENGTH_LONG).show();
new HttpAsyncTask()
.execute("http://demo.glowsosl.com/synchs_dsda_app/insert_details_msg.php");
msg_adapter.notifyDataSetChanged();
}
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
Contacts person = new Contacts();
person.setPhone(Str_Phone);
person.setName(Str_Msg);
return POST(urls[0], person);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), result + "Data Sent!",
Toast.LENGTH_LONG).show();
}
}
private static String convertInputStreamToString(InputStream inputStream)
throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
public static String POST(String url, Contacts person) {
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("contact_no", person.getPhone());
jsonObject.accumulate("sim_num", "Unknown");
jsonObject.accumulate("msg", person.getName());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the
// content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result + "," + person.getName() + ","
+ person.getPhone();
}
ArrayList<String> jsonStringToArray(String jsonString) throws JSONException {
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray jsonArray = new JSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++) {
stringArray.add(jsonArray.getString(i));
}
return stringArray;
}
public void fetchInbox() {
// ArrayList sms = new ArrayList();
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor cursor = getContentResolver().query(uriSms,
new String[] { "_id", "address", "date", "body" }, null, null,
null);
//for (int i =0; i<((JSONArray) cursor).length();i++){
//Toast.makeText(getApplicationContext(), "work", Toast.LENGTH_SHORT).show();
//}
cursor.moveToFirst();
while (cursor.moveToNext()) {
String address = cursor.getString(1);
String date = cursor.getString(2);
String body = cursor.getString(3);
// Toast.makeText(getApplicationContext(), cursor.getString(2), Toast.LENGTH_SHORT).show();
msg_list.add(new Message_Item(address, body,date));
}
msg_adapter = new Msg_adapter(msg_list, message_class.this);
lstView.setAdapter(msg_adapter);
}
Instead of applying for loop out side async task use it in doInBackground method.
Your doInBackground method will look like follows.
#Override
protected String doInBackground(String... urls) {
String result="";
for(int i = 0; i < msg_list.size(); i++){
Str_Msg = msg_list.get(i).getStrMsg().toString();
Str_Phone = msg_list.get(i).getStrNumber().toString();
Contacts person = new Contacts();
person.setPhone(Str_Phone);
person.setName(Str_Msg);
result= result + POST(urls[0], person);
}
return result;
}
And call this async task only once.
Enjoy!!

how do i pass user-defined array parameter to asynctask in android

However, when i just check the user-defined array parameter, customerList in the outer class there are values inside but the uploadAsyncTask innerclass keeps failing on the emulator (displaying unfortunately the app has failed).
private ArrayList<CustomerData> customerList = new ArrayList<CustomerData>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DBAdapter(this);
presidents = getResources().getStringArray(R.array.presidents_array);
client = new AsyncHttpClient();
Button btn_Save, btn_Backup;
btn_Save = (Button) findViewById(R.id.btnSave);
btn_Backup = (Button) findViewById(R.id.btnBackup);
txt_AcctNum = (TextView) findViewById(R.id.txtAcctNum);
txt_AcctName = (TextView) findViewById(R.id.txtAcctName);
s1 = (Spinner) findViewById(R.id.spinner);
txt_Amt = (TextView) findViewById(R.id.txtAmt);
/*
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, presidents);
*/
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_single_choice, presidents);
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int arg2, long arg3) {
int index = arg0.getSelectedItemPosition();
//Toast.makeText(getBaseContext(),
// "You have selected item : " + presidents[index],
// Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
-------other codes here----
btn_Backup.setOnClickListener(new Button.OnClickListener() {
#SuppressWarnings(value = "unchecked")
public void onClick(View view) {
ArrayList<CustomerData> custList = new ArrayList<CustomerData>();
// db = new DBAdapter(context);
db.open();
//db.backupToSD();
//---get all contacts---
Cursor c = db.getAllCustomers();
if (c.moveToFirst()) {
do {
//DisplayContact(c);
//sendData();
custList = addAndDisplayCustomer(c);
} while (c.moveToNext());
}
/* for (int i = 0; i < custList.size(); i++) {
Toast.makeText(getApplicationContext(), "---Customer Data--- " + "id: " +
custList.get(i).getId() + " Acct Name: " +
custList.get(i).getAcctName() + " Acct Num: " +
custList.get(i).getAcctNum() + " Tnx type: " +
custList.get(i).getTxnType() + " Amt: " +
custList.get(i).getAmt(), Toast.LENGTH_LONG).show(); }*/
Toast.makeText(getApplicationContext(), " Uploading data ... " + custList.get(0).getId(), Toast.LENGTH_LONG).show();
UploadASyncTask upload = new UploadASyncTask();
upload.execute(custList);
}
public ArrayList<CustomerData> addAndDisplayCustomer(Cursor c)
{
CustomerData customer = new CustomerData(c.getString(0), c.getString(1),
c.getString(2), c.getString(3), c.getString(4));
customerList.add(customer);
return customerList;
}
//int delRows = db.deleteAll();
//db.backupToSD();
//db.dropTable();
//Toast.makeText(getApplicationContext(), " Table successfully dropped ! ", Toast.LENGTH_LONG).show();
//db.close();
});
}
private class UploadASyncTask extends AsyncTask<ArrayList<CustomerData>, Void, Void> {
private Cursor c;
private String id;
private String acct_Name ;
private String acct_Num;
private String txnType;
private String amt;
//private ArrayList<CustomerData> custList;
private Context mContext1;
private ProgressDialog dialog = null;
private Context mContext = null;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(MainActivity.this);
dialog.setTitle(" Sending to the server... ");
dialog.setMessage("Please wait...");
dialog.setProgressDrawable(mContext.getWallpaper());
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setCancelable(false);
dialog.show();
}
#Override
#SafeVarargs
final protected Void doInBackground(ArrayList<CustomerData>... custList) {
try {
ArrayList<CustomerData> custom = custList[0];
for (int i = 0; i<custom.size(); i++) {
String id = custom.get(i).getId();
String acct_Name = custom.get(i).getAcctName();
String acct_Num = custom.get(i).getAcctNum();
String txnType = custom.get(i).getTxnType();
String amt = custom.get(i).getAmt();
/*runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Welcome guy: " + id,
Toast.LENGTH_LONG).show();
}
});*/
HttpParams params = new BasicHttpParams();
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost httpPost = new HttpPost
("http://10.0.2.2:8080/RestWebService/rest/customer");
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("id", id));
postParams.add(new BasicNameValuePair("acct_name", acct_Name));
postParams.add(new BasicNameValuePair("acct_num", acct_Num));
postParams.add(new BasicNameValuePair("txn_type", txnType));
postParams.add(new BasicNameValuePair("amt", amt));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
entity.setContentEncoding(HTTP.UTF_8);
httpPost.setEntity(entity);
HttpResponse httpResponse = httpclient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
String result = "";
id = "";
acct_Name = "";
acct_Num = "";
txnType = "";
amt = "";
}
}
catch (Exception e)
{
Log.e("Server Error: ",e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
//custList.clear();
dialog.dismiss();
}
}
}
When I saw your code : there is a little problem. I don't know it's the good answer but :
private Context mContext = null;
and
dialog.setProgressDrawable(mContext.getWallpaper());
It's a nullPointerException in this line
For me You can delete the context and the cursor on your AsyncTask. Create a constructor on your AsyncTask and put the context in parameters, use it for the progressDialog
Hope it's help

update android rate bar

I have an android rate bar that is inflated into an layout. When I run the code, I get the rating I want to update the rateBar with from json and I check with my log to see that I actually get a rating, which I do. But when I try:
RatingBar ratingBar = (RatingBar) ((Activity) c).findViewById(R.id.beerRatingBar);
ratingBar.setNumStars(beerRate);
It does not update the rateBar on the activity.
My activity is beer page:
public class BeerPage extends Activity {
BeerData e;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.beer_page);
//get data from listview
Intent intent = getIntent();
Bundle b = intent.getExtras();
e = b.getParcelable("myBeerObject");
//prepare buttons
Button buttonBrewery = (Button) findViewById(R.id.buttonBrewery);
Button buttonStyle = (Button) findViewById(R.id.buttonStyle);
//prepare text things
TextView tv1 = (TextView) findViewById(R.id.beerTitle);
TextView tv2 = (TextView) findViewById(R.id.beerDescription);
TextView tv_ibu = (TextView) findViewById(R.id.IBU);
TextView tv_abv = (TextView) findViewById(R.id.abv);
TextView tv_glass = (TextView) findViewById(R.id.glass);
//set text thinsg
tv1.setText(e.beerName);
tv2.setText(e.beerDescription);
buttonBrewery.setText(e.beerBreweryName);
buttonStyle.setText(e.beerStyle);
tv_ibu.setText(e.beerIBU);
tv_abv.setText(e.beerABV);
tv_glass.setText(e.beerGlass);
//Toast.makeText(this, e.mediumLabel, Toast.LENGTH_SHORT).show();
//set image
ImageView im1 = (ImageView) findViewById(R.id.image);
ImageDownloadTask imageD = new ImageDownloadTask(im1);
imageD.execute(e.largeLabel);
//test shared prefs
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
//check if user has beer
String url = myURL;
String userURLComp = user;
String beerID = beerID;
url = url + userURLComp + beerID;
Log.d("lat", e.beerBreweryLat);
Log.d("long", e.beerBreweryLong);
new CheckBeerJSON(this,e).execute(url);
}
//view brewery function
public void viewBrewery(View view) {
// launch new brewery page class
Intent i = new Intent(this, BreweryPage.class);
i.putExtra("myBeerObject", e);
i.setClass(this, BreweryPage.class);
startActivity(i);
}
public void viewStyle(View view) {
// launch new brewery page class
Intent i = new Intent(this, BreweryPage.class);
i.putExtra("myBeerObject", e);
i.setClass(this, StylePage.class);
startActivity(i);
}
public String encodeThisWord(String word){
try {
word = URLEncoder.encode(word, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return word;
}
public void addBeer(View view){
//get user info
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
//get beer details
String url = url2;
String urlUserID = userID;
String urlBeerID = beer + e.beerId;
String urlBeerName = beerName + encodeThisWord(e.beerName);
//construct url for adding beer
url = url + urlUserID + urlBeerID + urlBeerName;
Log.d("url", url);
//execute async on url to add to brewery
new AddBeer(this).execute(url);
//to do: change to start rater
}
}
GetUserRating is where I get the rating to put into the rateBar:
public class GetUserRating extends AsyncTask
<String, Void, String> {
Context c;
public GetUserRating(Context context)
{
c = context;
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPostExecute(String result){
int beerRate = 0;
//parse json for value
try{
JSONObject json = new JSONObject(result);
beerRate = json.getInt("rate");
}
catch(Exception e){
}
Log.d("logIN", "the rating: " + beerRate);
//change rating
RatingBar ratingBar = (RatingBar) ((Activity) c).findViewById(R.id.beerRatingBar);
ratingBar.setNumStars(beerRate);
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
I found out my problem, I was changing the number of stars shown with this:
ratingBar.setNumStars(beerRate);
Which was in fact changing the number of stars shown. I wanted to highlight a certain number of the 5 stars shown, not change the number of stars shown.
What I really wanted to do was set the stars with:
r.setRating(beerRate);
I think that update a view item in an asyncTasck directly is a bad idea.
I suggest to create a public static member in BeerPage to update the beer rating.
Regards

Categories