This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have code that gets an image by its name from drawables, but for some reason it can't update it.
package com.infonuascape.osrshelper.fragments;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.toolbox.ImageLoader;
import com.infonuascape.osrshelper.R;
import com.infonuascape.osrshelper.activities.MainActivity;
import com.infonuascape.osrshelper.models.Account;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
public class BankViewFragment extends OSRSFragment {
private static final String TAG = "BankViewFragment";
private static Account account;
private ListView lv;
private ImageView iv;
Handler handler;
ArrayList<HashMap<String, String>> ItemList;
public static BankViewFragment newInstance(final Account account) {
BankViewFragment fragment = new BankViewFragment();
Bundle b = new Bundle();
fragment.setArguments(b);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.bank_view, null);
ItemList = new ArrayList<>();
new GetItems().execute();
lv = (ListView) view.findViewById(R.id.list);
handler = new Handler(Looper.getMainLooper());
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String nikas = sharedPref.getString("bankname", "null");
return view;
}
public static int getResId(String resourceName, Class<?> c) {
try {
Field idField = c.getDeclaredField(resourceName);
return idField.getInt(idField);
} catch (Exception e) {
throw new RuntimeException("No resource ID found for: "
+ resourceName + " / " + c, e);
}
}
private class GetItems extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
SharedPreferences sharedpreferences = getContext().getSharedPreferences("minescape", Context.MODE_PRIVATE);
String nikas = sharedpreferences.getString("bankname", "null");
String url = "https://api.minesca.pe/game/classic/stats?username=" + nikas;
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "NIKAS: " + nikas);
Log.e(TAG, "ACCOUNT: " + account);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject items = jsonObj.getJSONObject("bank");
Iterator keys = items.keys();
while(keys.hasNext()) {
String dynamicKey = (String)keys.next();
JSONObject line = items.getJSONObject(dynamicKey);
String item = line.getString("item");
//Integer image = getResId(item, Drawable.class);
final Integer image = getResources().getIdentifier(item, "drawable", getActivity().getPackageName());
String amount = line.getString("amount");
Log.e(TAG, "DAIKTAS: " + item);
Log.e(TAG, "KIEKIS: " + amount);
HashMap<String, String> contact = new HashMap<>();
String itembank = item.replaceAll("i_", "");
String itembanks = itembank.replaceAll("_", " ");
contact.put("name", itembanks);
contact.put("email", amount);
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.bank_view, null);
lv = (ListView) view.findViewById(R.id.list);
// iv = (ImageView) view.findViewById(R.id.logo);
final ImageView ims = (ImageView) lv.findViewById(R.id.logo);
handler.post(new Runnable() {
public void run() {
if(image != null) {
Log.e(TAG, "kas cia jam netinka?: " + image);
if(image == 0) {
ims.setImageResource(R.drawable.i_noted);
Log.e(TAG, "kas cia jam netinka?: " + image);
} else {
Log.e(TAG, "kas cia jam netinka?: " + image);
ims.setImageResource(image);
}
} else {
Log.e(TAG, "null?: " + image);
}
}
});
ItemList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
};
}
} else {
Log.e(TAG, "Couldn't get json from server.");
new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(),
"Couldn't get json from server!",
Toast.LENGTH_LONG).show();
}
};
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(getContext(), ItemList,
R.layout.list_item, new String[]{ "email","name"},
new int[]{R.id.email, R.id.name});
lv.setAdapter(adapter);
}
}
}
Error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.infonuascape.osrshelper, PID: 31024
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
at com.infonuascape.osrshelper.fragments.BankViewFragment$GetItems$1.run(BankViewFragment.java:128)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5637)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
The problem is that there's a lot of items, and most of them have the resources, but some don't and i would like to just skip those who don't have, but the main problem is that the app crashes while trying to see the bank.
Yes i have tried to solve my question using similar posts(duplicates), but none of them helped me.
Use this
final ImageView ims = (ImageView) view.findViewById(R.id.logo);
Instead of this
final ImageView ims = (ImageView) lv.findViewById(R.id.logo);
Related
I am trying to use if else in a spinner layout in android. But the if condition is never accepted with a given condition.
Id of spinner is stateView.
stateView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
State = String.valueOf(stateView.getSelectedItem());
try {
if(obj.getString("state").equals(State)){
Log.d("error",State);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
The same code works everywhere else in the block.
I assume the problem is in
if(obj.getString("state").equals(State))
If it is used if(true) the block works correctly, that means code is reaching there but there is a problem in the condition applied int the if statement.
even the below code is not working
if(obj.getString("state").equals("Delhi"))
this code is working outside the listener
private void stateData(final String stateName, final String cityName) {
final RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(this);
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, arrayResponse -> {
try {
for (int i = 0; i < arrayResponse.length(); i++) {
JSONObject obj = arrayResponse.getJSONObject(i);
if (obj.getString("state").equals(stateName)){
Log.d("error","working");
}
The whole code for reference
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.VoiceInteractor;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
TextView stateActiveCases, stateConfirmed, stateDeceased, stateRecovered, cChanges, rChanges, dChanges;
String State;
Spinner stateView;
FusedLocationProviderClient fusedLocationProviderClient;
RecyclerView recyclerView;
RecyclerView.Adapter<DistrictAdapter.ViewHolder> mAdapter;
RecyclerView.LayoutManager layoutManager;
List<Districts> districtsList;
ArrayList<String> States;
#SuppressLint("SourceLockedOrientationActivity")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.list);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
districtsList = new ArrayList<>();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MainActivity.this);
final TextView Total = findViewById(R.id.textView4);
final TextView Recovered = findViewById(R.id.textView5);
final TextView Death = findViewById(R.id.textView6);
final TextView TodayCases = findViewById(R.id.textView7);
final TextView TodayDeath = findViewById(R.id.textView8);
final TextView ActiveCases = findViewById(R.id.textView10);
stateActiveCases = findViewById(R.id.textView29);
stateView = findViewById(R.id.spinner);
stateConfirmed = findViewById(R.id.textView26);
stateRecovered = findViewById(R.id.textView27);
stateDeceased = findViewById(R.id.textView28);
cChanges = findViewById(R.id.textView14);
rChanges = findViewById(R.id.textView15);
dChanges = findViewById(R.id.textView16);
States = new ArrayList<>();
RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "https://coronavirus-19-api.herokuapp.com/countries/india", null, objectResponse -> {
try {
int cases = objectResponse.getInt("cases");
int recovered = objectResponse.getInt("recovered");
int deaths = objectResponse.getInt("deaths");
int todayCases = objectResponse.getInt("todayCases");
int todayDeaths = objectResponse.getInt("todayDeaths");
int activeCases = objectResponse.getInt("active");
Total.setText(String.valueOf(cases));
Death.setText(String.valueOf(deaths));
Recovered.setText(String.valueOf(recovered));
String tc = ("+" + todayCases);
String td = ("+" + todayDeaths);
TodayCases.setText(tc);
TodayDeath.setText(td);
ActiveCases.setText(String.valueOf(activeCases));
} catch (JSONException ex) {
ex.printStackTrace();
}
}, error -> Log.d("error", "something fishy " + error));
requestQueue.add(jsonObjectRequest);
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 2199);
} else {
getLocation();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 2199) {
getLocation();
}
}
private void getLocation() {
fusedLocationProviderClient.getLastLocation().addOnCompleteListener(task -> {
Location location = task.getResult();
if (location != null) {
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocation(
location.getLatitude(), location.getLongitude(), 1
);
stateData(addresses.get(0).getAdminArea(), addresses.get(0).getLocality());
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private void stateData(final String stateName, final String cityName) {
final RequestQueue requestQueue;
requestQueue = Volley.newRequestQueue(this);
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, "https://api.covidindiatracker.com/state_data.json", null, arrayResponse -> {
try {
for (int i = 0; i < arrayResponse.length(); i++) {
JSONObject obj = arrayResponse.getJSONObject(i);
if (obj.getString("state").equals(stateName)) {
stateActiveCases.setText(String.valueOf(obj.getInt("active")));
stateConfirmed.setText(String.valueOf(obj.getInt("confirmed")));
stateRecovered.setText(String.valueOf(obj.getInt("recovered")));
stateDeceased.setText((String.valueOf(obj.getInt("deaths"))));
String stateCChanges, stateRChanges, stateDChanges;
stateCChanges = "+" + obj.getInt("cChanges");
stateRChanges = "+" + obj.getInt("rChanges");
stateDChanges = "+" + obj.getInt("dChanges");
cChanges.setText(stateCChanges);
rChanges.setText(stateRChanges);
dChanges.setText(stateDChanges);
JSONArray array = obj.getJSONArray("districtData");
for (int j = 0; j < array.length(); j++) {
Districts districts = new Districts();
JSONObject obj1 = array.getJSONObject(j);
if (obj1.getString("name").equals(cityName)) {
districts.setName(obj1.getString("name"));
districts.setConfirmed((obj1.getInt("confirmed")));
districtsList.add(districts);
}
}
for (int k = 0; k < array.length(); k++) {
Districts districts = new Districts();
JSONObject obj1 = array.getJSONObject(k);
if (obj1.getString("name").equals(cityName)) {
continue;
}
districts.setName(obj1.getString("name"));
districts.setConfirmed(obj1.getInt("confirmed"));
districtsList.add(districts);
}
}
String state=obj.getString("state");
States.add(state);
stateView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
State = String.valueOf(stateView.getSelectedItem());
((TextView )parent.getChildAt(0)).setTextColor(ContextCompat.getColor(getApplicationContext(),R.color.colorAccent));
((TextView)parent.getChildAt(0)).setTextSize(16);
try {
if(obj.getString("state").equals(State)){
Log.d("error",State);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, States);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
stateView.setAdapter(arrayAdapter);
int spinner = arrayAdapter.getPosition(stateName);
stateView.setSelection(spinner);
} catch (JSONException e) {
e.printStackTrace();
}
mAdapter = new DistrictAdapter(districtsList);
recyclerView.setAdapter(mAdapter);
}, error -> Log.d("error", "something fishy " + error));
requestQueue.add(jsonArrayRequest);
}
}
I want to move the if statement inside the listener such that when I select a state the data for that state is displayed. right now I am getting state data from the parameter which fetches data from GPS location.
Check the whole project on
Github
Any other suggestions are welcome.
Thanks in advance.
I am trying to send an image and some string values from android to a php script using HttpURLConnection. I have successfully done so with strings, but can't seem to get it right with the image. I am using Base64 (android.util.Base64) to convert my image to a string to send it. Now, I have a separate HttpParse.java file I use to send all my info to the server, and I think that is where the change needs to be made to allow the image, but I'm not sure, (I am newer to java/android development). I've researched several similar questions, but they aren't fully clicking for me for what I'm doing wrong. Also, I have tested that I am successfully converting the image to a string. Here is my code:
EDIT I got a little farther... After testing, I am getting the issue because the three variables I try to get with getArguments() are coming back as null... But, I can't figure out how to get them to come through successfully... I added the code for how I start my fragment and how I try to get my bundle
My fragment start:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_units);
Intent intent = getIntent();
LexaUser = intent.getStringExtra("UserName");
ReadOnly = intent.getStringExtra("ReadOnly");
Password = intent.getStringExtra("Password");
QA = intent.getStringExtra("QA");
SearchValue = intent.getStringExtra("SearchInput");
bottomNavigation = (BottomNavigationView)findViewById(R.id.bottom_navigation);
bottomNavigation.inflateMenu(R.menu.bottom_menu);
fragmentManager = getSupportFragmentManager();
bottomNavigation.getMenu().getItem(0).setChecked(true);
UnitDetailsHeader = findViewById(R.id.UnitDetailsViewTitle);
UnitDetailsHeader.setText(SearchValue);
UnitSizeText = findViewById(R.id.UnitSize);
UnitStatusText = findViewById(R.id.UnitStatus);
if (SearchValue.contains("-")) {
getUnitDetails(SearchValue, LexaUser);
} else {
getSiblings();
}
bottomNavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.action_search:
fragment = new NewUnitStatusFragment();
break;
case R.id.action_cart:
fragment = new PendingUnitStatusFragment();
break;
case R.id.action_hot_deals:
fragment = new FinalUnitStatusFragment();
break;
case R.id.action_siblings:
fragment = new SiblingUnitFragment();
break;
}
Bundle connBundle = new Bundle();
connBundle.putString("SearchValue", SearchValue);
connBundle.putString("LexaUser", LexaUser);
connBundle.putString("Password", Password);
connBundle.putString("QA", QA);
fragment.setArguments(connBundle);
final FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_container, fragment).commit();
return true;
}
});
}
And where I try to get my arguments: (I originally had in onCreateView but then tried to move it to onCreate. But the behavior was the same)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
SearchValue = getArguments().getString("SearchValue");
LexaUser = getArguments().getString("LexaUser");
Password = getArguments().getString("Password");
}
}
My fragment where I get the image and send my data:
package [my_package];
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import android.util.Base64;
import java.util.HashMap;
import static android.app.Activity.RESULT_OK;
public class NewUnitStatusFragment extends Fragment {
Context newUnitStatusContext;
Activity newUnitStatusActivity;
Intent cameraIntent;
ProgressDialog progressDialog;
String ReadOnly;
String LexaUser;
String Password;
String SearchValue;
String finalResultNewUnitStatus;
String HttpURLNewUnitStatus = "https://[path/to/file]/insertNewUnitStatus.php";
HashMap<String, String> hashMapNewUnitStatus = new HashMap<>();
HttpParse httpParse = new HttpParse();
Spinner statusSpinner;
Spinner generalCauseSpinner;
EditText newUSComment;
Button addPhotoBtn;
ImageView newUnitStatusImage;
Button addNewUnitStatus;
String newUnitStatus;
String generalCause;
String newUnitStatusComment;
String newUnitStatusPhoto;
String message;
private static final int PICK_FROM_GALLERY = 1;
public NewUnitStatusFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_newunitstatus, container, false);
newUnitStatusContext = getContext();
newUnitStatusActivity = getActivity();
statusSpinner = view.findViewById(R.id.Status);
generalCauseSpinner = view.findViewById(R.id.GeneralCause);
newUSComment = view.findViewById(R.id.NewComment);
newUnitStatusImage = view.findViewById(R.id.AddPhoto);
addPhotoBtn = view.findViewById(R.id.AddPhotosLabel);
addNewUnitStatus = view.findViewById(R.id.addBtnNewUnitStatus);
ArrayAdapter<CharSequence> statusSpinnerAdapter = ArrayAdapter.createFromResource(newUnitStatusContext,
R.array.new_unit_status_array, android.R.layout.simple_spinner_item);
statusSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
statusSpinner.setAdapter(statusSpinnerAdapter);
newUnitStatus = statusSpinner.getSelectedItem().toString();
ArrayAdapter<CharSequence> generalCauseSpinnerAdapter = ArrayAdapter.createFromResource(newUnitStatusContext,
R.array.status_general_cause_array, android.R.layout.simple_spinner_item);
generalCauseSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
generalCauseSpinner.setAdapter(generalCauseSpinnerAdapter);
generalCause = generalCauseSpinner.getSelectedItem().toString();
addPhotoBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startGallery();
}
});
// Set a click listener for the text view
addNewUnitStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
newUnitStatus = statusSpinner.toString();
generalCause = generalCauseSpinner.toString();
newUnitStatusComment = newUSComment.toString();
if (getArguments() != null) {
SearchValue = getArguments().getString("SearchValue");
LexaUser = getArguments().getString("LexaUser");
Password = getArguments().getString("Password");
}
addNewUnitStatus(SearchValue, newUnitStatus, generalCause, newUnitStatusComment, newUnitStatusPhoto, LexaUser, Password);
}
});
return view;
}
private void startGallery() {
cameraIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
cameraIntent.setType("image/*");
cameraIntent.setAction(Intent.ACTION_GET_CONTENT);
if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(cameraIntent, 1000);
} else {
Toast.makeText(newUnitStatusContext, "Error: " + cameraIntent + " - cameraIntent.resolveActivity(getActivity().getPackageManager()) = null", Toast.LENGTH_LONG).show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//super method removed
if (resultCode == RESULT_OK) {
if (requestCode == 1000) {
Uri returnUri = data.getData();
try {
Bitmap bitmapImage = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), returnUri);
newUnitStatusImage.setImageBitmap(bitmapImage);
newUnitStatusImage.buildDrawingCache();
Bitmap bm = newUnitStatusImage.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
newUnitStatusPhoto = Base64.encodeToString(b, Base64.DEFAULT);
} catch (IOException ioEx) {
ioEx.printStackTrace();
Toast.makeText(newUnitStatusContext, "ioEx Error: " + ioEx, Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(newUnitStatusContext, "Error: " + requestCode, Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(newUnitStatusContext, "Error: " + resultCode, Toast.LENGTH_LONG).show();
}
}
public void addNewUnitStatus(String searchInput, String newUnitStatus, String generalCause, String newUnitStatusComment, String newUnitStatusPhoto, String lexaUser, String password) {
class NewUnitStatusClass extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(newUnitStatusContext, "Loading Data", null, true, true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
if (httpResponseMsg != null) {
try {
JSONObject object = new JSONObject(httpResponseMsg);
message = object.getString("message");
Toast.makeText(newUnitStatusContext, httpResponseMsg, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
Toast.makeText(newUnitStatusContext, "Error: " + e.toString(), Toast.LENGTH_LONG).show();
} // catch (JSONException e)
progressDialog.dismiss();
} else {
progressDialog.dismiss();
Toast.makeText(newUnitStatusContext, "HttpResponseMsg is null.", Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... params) {
hashMapNewUnitStatus.put("searchinput", params[0]);
hashMapNewUnitStatus.put("newUnitStatus", params[1]);
hashMapNewUnitStatus.put("generalCause", params[2]);
hashMapNewUnitStatus.put("newUnitStatusComment", params[3]);
hashMapNewUnitStatus.put("newUnitStatusPhoto", params[4]);
hashMapNewUnitStatus.put("lexauser", params[5]);
hashMapNewUnitStatus.put("password", params[6]);
finalResultNewUnitStatus = httpParse.postRequest(hashMapNewUnitStatus, HttpURLNewUnitStatus);
return finalResultNewUnitStatus;
}
}
NewUnitStatusClass newUnitStatusClass = new NewUnitStatusClass();
newUnitStatusClass.execute(searchInput, newUnitStatus, generalCause, newUnitStatusComment, newUnitStatusPhoto, lexaUser, password);
}
}
And my code to do that actuall HttpURLConnection: HttpParse.java
package [my_package];
import android.app.ListActivity;
import android.widget.ArrayAdapter;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
public class HttpParse extends ListActivity {
String FinalHttpData = "";
String Result;
BufferedWriter bufferedWriter;
OutputStream outputStream;
BufferedReader bufferedReader;
StringBuilder stringBuilder = new StringBuilder();
URL url;
public String postRequest(HashMap<String, String> Data, String HttpUrlHolder) {
try {
url = new URL(HttpUrlHolder);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(14000);
httpURLConnection.setConnectTimeout(14000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
outputStream = httpURLConnection.getOutputStream();
bufferedWriter = new BufferedWriter(
new OutputStreamWriter(outputStream, "UTF-8"));
bufferedWriter.write(FinalDataParse(Data));
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
bufferedReader = new BufferedReader(
new InputStreamReader(
httpURLConnection.getInputStream()
)
);
FinalHttpData = bufferedReader.readLine();
}
else {
FinalHttpData = "Something Went Wrong";
}
} catch (Exception e) {
e.printStackTrace();
}
return FinalHttpData;
}
public String FinalDataParse(HashMap<String,String> hashMap2) throws UnsupportedEncodingException {
for(Map.Entry<String,String> map_entry : hashMap2.entrySet()){
stringBuilder.append("&");
stringBuilder.append(URLEncoder.encode(map_entry.getKey(), "UTF-8"));
stringBuilder.append("=");
stringBuilder.append(URLEncoder.encode(map_entry.getValue(), "UTF-8"));
}
Result = stringBuilder.toString();
return Result ;
}
}
All help is appreciated! Thank you!
P.S. my app shows the following error:
W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
This then leads to this:
E/JSONException: Error: org.json.JSONException: End of input at character 0 of
please help how can i solve that in \AboutActivity.java
in the line :
imageLoader.DisplayImage(Constant.SERVER_IMAGE_NEWSLISTDETAILS+about.getComLogo().toString(), imglogo);
the problem in messages gradle builder :
Error:Error: Expected resource of type string [ResourceType]
package com.freeimages.hdpicturs;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.hdpictursfree.imageloader.ImageLoader;
import com.hdpictursfree.item.ItemAbout;
import com.hdpictursfree.util.AlertDialogManager;
import com.hdpictursfree.util.Constant;
import com.hdpictursfree.util.JsonUtils;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class AboutActivity extends ActionBarActivity {
ImageView imglogo;
TextView txtappname,txtcomemail,txtcomsite;
WebView webcomdes;
public ImageLoader imageLoader;
JsonUtils util;
List<ItemAbout> listabout;
AlertDialogManager alert = new AlertDialogManager();
Toolbar toolbar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
toolbar = (Toolbar) this.findViewById(R.id.toolbar);
toolbar.setTitle("About Us");
this.setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
imglogo=(ImageView)findViewById(R.id.image_comlogo);
txtappname=(TextView)findViewById(R.id.text_appname);
txtcomemail=(TextView)findViewById(R.id.text_comemail);
txtcomsite=(TextView)findViewById(R.id.text_comwebsite);
webcomdes=(WebView)findViewById(R.id.webView_comdes);
webcomdes.getSettings().setDefaultTextEncodingName("UTF-8");
listabout=new ArrayList<ItemAbout>();
imageLoader=new ImageLoader(getApplicationContext());
util=new JsonUtils(getApplicationContext());
if (JsonUtils.isNetworkAvailable(AboutActivity.this)) {
new MyTask().execute(Constant.COMPANY_DETAILS_URL);
} else {
showToast("No Network Connection!!!");
alert.showAlertDialog(AboutActivity.this, "Internet Connection Error",
"Please connect to working Internet connection", false);
}
}
private class MyTask extends AsyncTask<String, Void, String> {
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AboutActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
return JsonUtils.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (null != pDialog && pDialog.isShowing()) {
pDialog.dismiss();
}
if (null == result || result.length() == 0) {
showToast("Server Connection Error");
alert.showAlertDialog(AboutActivity.this, "Server Connection Error",
"May Server Under Maintaines Or Low Network", false);
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(Constant.CATEGORY_ARRAY_NAME);
JSONObject objJson = null;
for (int i = 0; i < jsonArray.length(); i++) {
objJson = jsonArray.getJSONObject(i);
ItemAbout objItem = new ItemAbout();
objItem.setAppName(objJson.getString(Constant.COMPANY_DETAILS_APPNAME));
objItem.setComEmail(objJson.getString(Constant.COMPANY_DETAILS_COMMAIL));
objItem.setComWebsite(objJson.getString(Constant.COMPANY_DETAILS_COMSITE));
objItem.setComDes(objJson.getString(Constant.COMPANY_DETAILS_COMDES));
objItem.setComLogo(objJson.getString(Constant.COMPANY_DETAILS_COMLOGO));
listabout.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
setAdapterToListview();
}
}
}
public void setAdapterToListview() {
ItemAbout about=listabout.get(0);
txtappname.setText(about.getAppName());
txtcomemail.setText(about.getComEmail());
txtcomsite.setText(about.getComWebsite());
String mimeType = "text/html";
String encoding = "utf-8";
String htmlText = about.getComDes();
String text = "<html><head>"
+ "<style type=\"text/css\">body{color: #1C1C1C;}"
+ "</style></head>"
+ "<body>"
+ htmlText
+ "</body></html>";
webcomdes.loadData(text, mimeType, encoding);
webcomdes.setBackgroundColor(Color.parseColor(getString(R.color.background_color)));
imageLoader.DisplayImage(Constant.SERVER_IMAGE_NEWSLISTDETAILS+about.getComLogo().toString(), imglogo);
}
public void showToast(String msg) {
Toast.makeText(AboutActivity.this, msg, Toast.LENGTH_LONG).show();
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem)
{
switch (menuItem.getItemId())
{
case android.R.id.home:
onBackPressed();
break;
default:
return super.onOptionsItemSelected(menuItem);
}
return true;
}
}
i am working on json parsing where in my TypeMenu java file i am getting response from server and when i click on the item in listview i should get related item in the next activity in listview ..that listview item is also coming from server...here i want to get item only from selected item..but i am getting all item from database in my next activity which is SubMenu.java...like if i select Pizza so in next activity i should get item related with pizza only
Here is my TypeMenu.java file
package com.example.zeba.broccoli;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class TypeMenu extends AppCompatActivity {
private String TAG = TypeMenu.class.getSimpleName();
String bid;
private ProgressDialog pDialog;
private ListView lv;
private static final String TAG_BID = "bid";
// URL to get contacts JSON
private static String url = "http://cloud.granddubai.com/brtemp/index.php";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_type_menu);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
HashMap<String, String> selected = contactList.get(position);
String keyId = new ArrayList<>(selected.keySet()).get(0);
String type_items = selected.get(keyId);
Intent in = new Intent(getApplicationContext(), SubMenu.class);
// sending pid to next activity
in.putExtra(TAG_BID ,type_items );
startActivityForResult(in, 100);
Toast.makeText(getApplicationContext(),"Toast" +type_items ,Toast.LENGTH_LONG).show();
}
});
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(TypeMenu.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
// Toast.makeText(getApplicationContext(),"Toast",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray jsonArry = new JSONArray(jsonStr);
for (int i = 0; i < jsonArry.length(); i++)
{
JSONObject c = jsonArry.getJSONObject(i);
String id = c.getString("id");
String type = c.getString("type");
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("type", type);
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing 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 errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
TypeMenu.this, contactList,
R.layout.list_item, new String[]{ "type","id"},
new int[]{
R.id.type,R.id.id});
lv.setAdapter(adapter);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
here is my SubMenu.java file
package com.example.zeba.broccoli;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class SubMenu extends AppCompatActivity {
private String TAG = SubMenu.class.getSimpleName();
String type_items ;
private ProgressDialog pDialog;
private ListView lv;
private static final String TAG_BID = "bid";
// URL to get contacts JSON
private static String url = "http://cloud.granddubai.com/broccoli/menu_typeitem.php";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_type_menu);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent i = getIntent();
// getting product id (pid) from intent
type_items = i.getStringExtra(TAG_BID);
Toast.makeText(getApplicationContext(),"Toast 12" + type_items ,Toast.LENGTH_LONG).show();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pDialog = new ProgressDialog(SubMenu.this);
pDialog.setMessage("Loading book details.");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
// getting values from selected ListItem
HashMap<String, String> selected = contactList.get(position);
String keyId = new ArrayList<>(selected.keySet()).get(0);
String type_items = selected.get(keyId);
//Intent in = new Intent(getApplicationContext(), SubMenu.class);
// sending pid to next activity
// in.putExtra(TAG_BID ,text);
//startActivityForResult(in, 100);
Toast.makeText(getApplicationContext(),"Toast" + type_items,Toast.LENGTH_LONG).show();
}
});
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(SubMenu.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
// Toast.makeText(getApplicationContext(),"Toast",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray jsonArry = new JSONArray(jsonStr);
for (int i = 0; i < jsonArry.length(); i++)
{
JSONObject c = jsonArry.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("name", name);
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing 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 errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
SubMenu.this, contactList,
R.layout.list_item, new String[]{ "name","id"},
new int[]{
R.id.type});
lv.setAdapter(adapter);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
here is my php file..i know it will show all the data ..i tried other code also but not working ..in this atleast all data from table is showing..but i want only selected data
<?php
if($_SERVER['REQUEST_METHOD']=='GET')
{
$id = $_GET['type_items'];
require_once('config.php');
$sql = "SELECT * FROM main_menu_items WHERE type_item='".$id."'";
$r = mysqli_query($con,$sql);
$res = mysqli_fetch_array($r);
$result = array();
array_push($result,array("name"=>$res['name'],)
);
echo json_encode(array("result"=>$result));
mysqli_close($con);
}
replace for loop of GetContacts of SubMenu.java class with below :
for (int i = 0; i < jsonArry.length(); i++) {
JSONObject c = jsonArry.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String type = c.getString("type");
if (type.equalsIgnoreCase(type_items)) {
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("name", name);
contactList.add(contact);
break;
}
}
In submenu class you need to check if the selected ID matches with the id just save that data in list and break the loop.
I wrote the code below, where the search for latitude and longitude is performed based on the address entered by the enduser.
The class CadastroClientes.java. It is responsible for seeking the user's address (HttpRequestTask method) and set this result to char_Logradouro field (textvfield).
After set the value in the mentioned field, BuscaGeolocalizacao class is called and the getAddressFromLocation method passing as parameter, the address you entered. So far everything was running right.
The problem started when in the BuscaGeolocalizacao class I tried to set the value of the result of latitude and longitude on the fields:
cc.char_Lat.setText(sb.append(address.getLatitude()));
cc.char_Long.setText(sb.append(address.getLongitude()));
CadastroClientes.java (first code called)
package com.clubee.doggywalker;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Handler;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.List;
public class CadastroClientes extends Activity {
//JSON node
private static final String TAG_SUCCESS = "success";
//url para cadastrar novo usuário
private static String url_cadastraCliente = "http://clubee.com.br/dev/dbDoggyWalker/DoggyWalker_CadastroCliente_Inserir.php";
JSONParser jsonParser = new JSONParser();
EditText char_Nome;
EditText char_CEP;
EditText char_Email;
EditText char_Cidade;
EditText char_Estado;
EditText char_Logradouro;
EditText char_Endereco;
EditText char_Bairro;
TextView char_Lat;
TextView char_Long;
//barra de progressão
private ProgressDialog pDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cadastro_dw);
char_Nome = (EditText) findViewById(R.id.inputNome);
char_Email = (EditText) findViewById(R.id.inputEmail);
char_Logradouro = (EditText) findViewById(R.id.inputLogradouro);
char_Cidade = (EditText) findViewById(R.id.inputCidade);
char_Estado = (EditText) findViewById(R.id.inputEstado);
char_Bairro = (EditText) findViewById(R.id.inputBairro);
char_CEP = (EditText) findViewById(R.id.inputCEP);
char_Lat = (TextView) findViewById(R.id.inputLatitude);
char_Long = (TextView) findViewById(R.id.inputLongitude);
//Criar botão
Button btnCadastraCliente = (Button) findViewById(R.id.btnCadastraCliente);
Button btnBuscaCEP = (Button) findViewById(R.id.btnBuscaEndereco);
//Criar evento do botão
btnCadastraCliente.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View view) {
//abre thread em background
new CadastraCliente().execute();
}
});
//Criar evento do botão
btnBuscaCEP.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View view) {
//abre thread em background
new HttpRequestTask().execute();
}
});
}
private class HttpRequestTask extends AsyncTask < Void, Void, DAOPostmon > {
String charCepTrim = char_CEP.getText().toString().trim();
final String url = "http://api.postmon.com.br/v1/cep/" + charCepTrim;
RestTemplate restTemplate = new RestTemplate();
#Override
protected DAOPostmon doInBackground(Void...params) {
try {
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
DAOPostmon DAOPostmon = restTemplate.getForObject(url, DAOPostmon.class);
return DAOPostmon;
} catch (Exception e) {
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
DAOPostmon DAOPostmon = restTemplate.getForObject(url, DAOPostmon.class);
return DAOPostmon;
}
}
#Override
protected void onPostExecute(DAOPostmon DAOPostmon) {
//quando a tag Logradouro estiver disponiivel no retorno da api rest
if (DAOPostmon.getLogradouro() == null) {
TextView greetingLogradouro = (TextView) findViewById(R.id.inputLogradouro);
TextView greetingBairro = (TextView) findViewById(R.id.inputBairro);
TextView greetingCidade = (TextView) findViewById(R.id.inputCidade);
TextView greetingEstado = (TextView) findViewById(R.id.inputEstado);
TextView greetingCEP = (TextView) findViewById(R.id.inputCEP);
greetingLogradouro.setText(DAOPostmon.getEndereco().toUpperCase());
greetingCidade.setText(DAOPostmon.getCidade().toUpperCase());
greetingBairro.setText(DAOPostmon.getBairro().toUpperCase());
greetingEstado.setText(DAOPostmon.getEstado().toUpperCase());
greetingCEP.setText(DAOPostmon.getCep());
} else {
//senão, quando não tiver a tag logradouro, usar endereco
TextView greetingLogradouro = (TextView) findViewById(R.id.inputLogradouro);
TextView greetingBairro = (TextView) findViewById(R.id.inputBairro);
TextView greetingCidade = (TextView) findViewById(R.id.inputCidade);
TextView greetingEstado = (TextView) findViewById(R.id.inputEstado);
TextView greetingCEP = (TextView) findViewById(R.id.inputCEP);
greetingLogradouro.setText(DAOPostmon.getLogradouro().toUpperCase());
greetingCidade.setText(DAOPostmon.getCidade().toUpperCase());
greetingBairro.setText(DAOPostmon.getBairro().toUpperCase());
greetingEstado.setText(DAOPostmon.getEstado().toUpperCase());
greetingCEP.setText(DAOPostmon.getCep());
}
String address = char_Logradouro.getText().toString();
BuscaGeolocalizacao locationAddress = new BuscaGeolocalizacao();
locationAddress.getAddressFromLocation(address,
getApplicationContext(), new GeocoderHandler());
}
}
private class GeocoderHandler extends Handler {
public void handlerMsg(Message message) {
String locationAddress;
switch (message.what) {
case 1:
Bundle bundle = message.getData();
locationAddress = bundle.getString("char_Logradouro");
char_Lat.setText(locationAddress);
break;
default:
locationAddress = null;
}
}
}
class CadastraCliente extends AsyncTask < String, String, String > {
/**
* Before starting background thread Show Progress Dialog
*/#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CadastroClientes.this);
pDialog.setMessage("Cadastrando usuário..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
*/
protected String doInBackground(String...args) {
String Nome = char_Nome.getText().toString();
String Email = char_Email.getText().toString();
String Endereco = char_Endereco.getText().toString();
String TipoLicenca = "DogWalker";
// Building Parameters
List < NameValuePair > params = new ArrayList < NameValuePair > ();
params.add(new BasicNameValuePair("char_Nome", Nome));
params.add(new BasicNameValuePair("char_Email", Email));
params.add(new BasicNameValuePair("char_Endereco", Endereco));
params.add(new BasicNameValuePair("char_TipoLicenca", TipoLicenca));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_cadastraCliente,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), CadastroClientes.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
BuscaGeolocalizacao.java (the class responsible to return lat/long)
package com.clubee.doggywalker;
import android.location.Geocoder;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class BuscaGeolocalizacao {
private static final String TAG = "GeocodingLocation";
public static void getAddressFromLocation(final String locationAddress,
final Context context, final Handler handler) {
Thread thread = new Thread() {
#Override
public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List<Address> addressList = geocoder.getFromLocationName(locationAddress, 1);
if (addressList != null && addressList.size() > 0) {
CadastroClientes cc = new CadastroClientes();
Address address = addressList.get(0);
StringBuilder sb = new StringBuilder();
sb.append(address.getLatitude()).append("\n");
sb.append(address.getLongitude()).append("\n");
result = sb.toString();
cc.char_Lat.setText(sb.append(address.getLatitude()));
cc.char_Long.setText(sb.append(address.getLongitude()));
}
} catch (IOException e) {
Log.e(TAG, "Unable to connect to Geocoder", e);
} finally {
Message message = Message.obtain();
message.setTarget(handler);
if (result != null) {
message.what = 1;
Bundle bundle = new Bundle();
result = "Address: " + locationAddress +
"\n\nLatitude and Longitude :\n" + result;
bundle.putString("address", result);
message.setData(bundle);
} else {
message.what = 1;
Bundle bundle = new Bundle();
result = "Address: " + locationAddress +
"\n Unable to get Latitude and Longitude for this address location.";
bundle.putString("address", result);
message.setData(bundle);
}
message.sendToTarget();
}
}
};
thread.start();
}
}
After the attempt to implement sending latitude and longitude for activity, the system started to explode with the following message
07-01 00:44:18.412 8978-9170/com.clubee.doggywalker E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-23081
Process: com.clubee.doggywalker, PID: 8978
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.(Handler.java:200)
at android.os.Handler.(Handler.java:114)
at android.app.Activity.(Activity.java:793)
at com.clubee.doggywalker.CadastroClientes.(CadastroClientes.java:27)
at com.clubee.doggywalker.BuscaGeolocalizacao$1.run(BuscaGeolocalizacao.java:33)
You can post on the UI thread also like
cc.char_Lat.post(new Runnable() {
#Override
public void run() {
cc.char_Lat.setText("what ever value");
}
});
But by the way i think you should use your handler instead of using a reference to CadastroClientes
do your UI operations in a UI Thread. Like this..
runOnUiThread(new Runnable() {
#Override
public void run() {
cc.char_Lat.setText(sb.append(address.getLatitude()));
cc.char_Long.setText(sb.append(address.getLongitude()));
}
});
Android basically works on two thread types namely UI thread and background thread. According to android documentation -
Do not access the Android UI toolkit from outside the UI thread to fix this problem, Android offers several ways to access the UI thread from other threads. Here is a list of methods that can help:
Activity.runOnUiThread(Runnable)
View.post(Runnable)
View.postDelayed(Runnable, long)
new Thread()
{
public void run()
{
myactivity.this.runOnUiThread(new runnable()
{
public void run()
{
cc.char_Lat.setText(sb.append(address.getLatitude()));
cc.char_Long.setText(sb.append(address.getLongitude()));
}
});
}
}.start();
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null) {
showAddress(location);
}
final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location loc) {
showAddress(loc);
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
};
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
private void showAddress(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder myLoc = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> mlist;
try {
mlist = myLoc.getFromLocation(latitude, longitude, 1);
if(mList.size() == 1) { char_Lat.SetText(mlist.get(0).getLatitude().toString()); char_Long.Settext(mlist.get(0).getLongitude().toString());
}
} catch (IOException e) {
// TODO Auto-generated catch block
log.e("IO Exception",e.Message);
}
}
use Location Permission in your Manifest :
android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION
http://developer.android.com/reference/android/Manifest.permission.html