Error parsing data JSON, Fragment Android Studio - json

Someone please help me why my result always error parsing data ?
My app run smoothly but does not display anything. i feel so stuck here.
this is my code
Sorry for bad english
API JSON
public function getkategori2(){
$data = array();
$token = $this->input->post('f_token');
$tabel = $this->input->post('f_tabel');
if ($token == '' || $tabel == ''){
$data['result'] = false;
$data['msg'] = "Data Kosong";
echo json_encode($data);
return;
}
$sql = 'SELECT * FROM '.$tabel.'_kategori INNER JOIN files WHERE '.$tabel.'_kategori.id_kategori = files.id_kategori';
$q = $this->db->query($sql);
if ($q->num_rows()>0) {
foreach ($q->result() as $value) {
$kategori = array(
'nama_kategori' => $value->nama_kategori,
'file_name' => $value->file_name,
);
};
$data['result'] = true;
$data['kategori_data'] = $kategori;
$data['msg'] = '';
} else {
$data['result'] = false;
$data['msg'] = 'error';
}
echo json_encode($data);
}
JSON Result
{
"result":true,
"kategori_data":
{
"nama_kategori":"Pasta",
"file_name":"1_Pasta.jpg"
},
"msg":""
}
KategoriAdapter
public class KategoriAdapter extends RecyclerView.Adapter<KategoriAdapter.ViewHolder> {
private ArrayList<Kategori> mData;
private Context context;
private SessionManager sesi;
public KategoriAdapter (Context context, ArrayList<Kategori> mData){
this.context = context;
this.mData = mData;
}
#Override
public KategoriAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View view = LayoutInflater.from(context)
.inflate(R.layout.item_list_kategori, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(KategoriAdapter.ViewHolder holder, int position) {
Kategori k = mData.get(position);
String kategori = k.getKategoriNama();
String gambar = k.getImg();
//masukan kedalam object viewholder
holder.tvKategori.setText(kategori);
Picasso.with(context)
.load(Constant.BASE_IMAGE + sesi.getTabel() + "/kategori/" + gambar)
.into(holder.ivKategori);
}
//buta object interface onAdapterjabatanListener
private OnAdapterListener listener;
//buat method untuk mendefiniskan listenernya
public void setListener(OnAdapterListener listener){
this.listener = listener;
}
#Override
public int getItemCount() {
return mData == null ? 0 : mData.size();
}
//buat class yang extend dari ViewHolder
class ViewHolder extends RecyclerView.ViewHolder{
public LinearLayout container;
public TextView tvKategori;
public ImageView ivKategori;
public ViewHolder(View v){
super(v);
//baru hubungkan variablenya dengan item yang ada di class layout item
container = v.findViewById(R.id.container);
tvKategori = v.findViewById(R.id.tvKategori);
ivKategori = v.findViewById(R.id.ivKategori);
}
}
KategoriFragment
public class KategoriFragment extends Fragment {
SessionManager sesi;
private ArrayList<Kategori> data;
private OkHttpClient okClient;
private RecyclerView rvData;
public KategoriFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_kategori, container, false);
sesi = new SessionManager(getActivity());
data = new ArrayList<>();
okClient = new OkHttpClient();
rvData = rootView.findViewById(R.id.rvData);
RecyclerView.LayoutManager manager = new LinearLayoutManager(getActivity());
rvData.setLayoutManager(manager);
getData();
return rootView;
}
private void getData(){
data.clear();
String url = Constant.BASE_URL + "getkategori2";
FormBody parameters = new FormBody.Builder()
.add("f_token", sesi.getToken())
.add("f_tabel", sesi.getTabel())
.build();
//buat request untuk ambil data
Request request = new Request.Builder()
.url(url)
.post(parameters)
.build();
okClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, final IOException e) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
e.printStackTrace();
RbHelpers.pesan(getActivity(),
"error :" + e.getMessage());
}
});
}
#Override
public void onResponse(Call call,final Response response) throws IOException {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
//hilangkan dialognya
}});
final String responData = response.body().string();
RbHelpers.pre("respon data : " + responData);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
//debug hasilnya kedalam android monitor
try {
//parsing json
try {
JSONObject json = new JSONObject(responData);
Log.d("tagJSON",json.toString());
//check hasilnya apakah true or false
boolean hasil = json.getBoolean("result");
if (hasil){
//ada datanya
//buat object jsonArray
JSONArray jArray = json.getJSONArray("kategori_data");
//looping data dan masukkan kedalam arraylist
for (int i = 0; i < jArray.length(); i++){
JSONObject jObj = jArray.getJSONObject(i);
Kategori kategori = new Kategori();
kategori.setKategoriNama(jObj.getString("nama_kategori"));
kategori.setImg(jObj.getString("file_name"));
//tinggal masukan ke arraylist
data.add(kategori);
}
} else {
String msg = json.getString("msg");
RbHelpers.pesan(getActivity(), msg);
}
//tinggal masukin ke recylerview
//UserAdapter adapter = new UserAdapter
KategoriAdapter adapter = new KategoriAdapter(getActivity(), data);
rvData.setAdapter(adapter);
} catch (JSONException e){
RbHelpers.pesan(getActivity(), "Error parsing data");
e.printStackTrace();
}
} catch (Exception e) {
RbHelpers.pesan(getActivity(), "Error ambil data");
e.printStackTrace();
}
}
});
}
});
}

Think this is the wrong part "kategori_data" is a JSONObject , not a JSONArray, Check the correct format in jsonBlob as
Here you have an example of a mine working project where i have a model Articulo(Product) and I make a request to retrieve that object data
try{
// Get the JSON array
JSONObject result = response.getJSONObject("articulo");
int i ;
for(i=0;i<1;i++){
JSONObject articulo = result;
ListaArticulos item = new ListaArticulos(
articulo.getString("IdArticulo"),
articulo.getString("Precio"),
articulo.getString("Stock"),
articulo.getString("Consultas"),
articulo.getString("IdCategoria"),
articulo.getString("Descripcion"),
articulo.getString("Observacion"),
articulo.getString("Codigo"),
articulo.getString("Imagen")
);
So in conclusion what you need to do is change JSONArray jArray = json.getJSONArray("kategori_data");
for
JSONObject jsonOb = json.getJSONObject("kategori_data");

Related

trying to fetch data from newsapi.org but ending up with 403 error, paramType 2048 not found etc

NetworkUtilities.java
public class NetworkUtilities {
private static final String TAG = NetworkUtilities.class.getSimpleName();
public static URL createUrl(String stringUrl){
URL url = null;
try{
url = new URL(stringUrl);
}catch (MalformedURLException e){
Log.v(TAG, "Problem building the Url");
}
return url;
}
public static String httpRequest(URL url) throws IOException{
String jsonResponse = "";
if(url ==null){
Log.v(TAG, "Url is null");
return jsonResponse;
}
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
try{
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
if(httpURLConnection.getResponseCode() == 200){
inputStream = httpURLConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
}
else{
Log.e(TAG, "Error response code" + httpURLConnection.getResponseCode());
}
}catch (IOException e){
Log.v(TAG, "Problem retrieving the json result", e);
}finally {
if(httpURLConnection != null){
httpURLConnection.disconnect();
}
if(inputStream != null){
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException{
StringBuilder output = new StringBuilder();
if(inputStream != null){
InputStreamReader in = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader bf = new BufferedReader(in);
String line = bf.readLine();
while(line != null){
output.append(line);
line = bf.readLine();
}
}
return output.toString();
}
public static List<String> extractFromJson(String jsonResponse){
if(TextUtils.isEmpty(jsonResponse)){
return null;
}
List<String> newsStories = new ArrayList<>();
try{
JSONObject baseObj = new JSONObject(jsonResponse);
JSONArray articlesArray = baseObj.getJSONArray("data");
for(int i=0;i<articlesArray.length();i++){
JSONObject currentArticle = articlesArray.getJSONObject(i);
JSONObject source = currentArticle.getJSONObject("source");
String sourceName = source.getString("name");
String title = currentArticle.getString("title");
String description = currentArticle.getString("description");
String newsStory = "Source" + sourceName + "/n" + title + "/n" + description;
newsStories.add(newsStory);
}
}catch (JSONException e){
Log.e(TAG, " Problem parsing the json string", e);
}
return newsStories;
}
NewsAdapter.java
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
private Context mContext;
private List<String> mNewsArticles;
NewsAdapter(Context context){
mContext = context;
}
#NonNull
#Override
public NewsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater
.from(mContext)
.inflate(R.layout.news_list_item,parent, false);
view.setFocusable(true);
return new NewsViewHolder(view);
}
#Override
public void onBindViewHolder( NewsViewHolder holder, int position) {
String currentArticle = mNewsArticles.get(position);
holder.mTextView.setText(currentArticle);
}
#Override
public int getItemCount() {
if(mNewsArticles != null){
return mNewsArticles.size();
}
return 0;
}
public class NewsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
final TextView mTextView;
public NewsViewHolder(#NonNull View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.textView);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "position :" + getLayoutPosition(), Toast.LENGTH_SHORT).show();
}
}
public void setNewsData(List<String> newsData){
mNewsArticles = newsData;
notifyDataSetChanged();
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private RecyclerView mRecyclerView;
private NewsAdapter mNewsAdapter;
private static final String BASE_URL = "https://newsapi.org/v2/top-headlines?country=us&apiKey=13f428d687714c33a24f34ad6c5***87";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(
new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
mRecyclerView.setHasFixedSize(true);
mNewsAdapter = new NewsAdapter(this);
mRecyclerView.setAdapter(mNewsAdapter);
new FetchNewsArticle().execute(BASE_URL);
}
public class FetchNewsArticle extends AsyncTask<String, Void, List<String>>{
#Override
protected List<String> doInBackground(String... strings) {
String stringUrl = strings[0];
URL url = NetworkUtilities.createUrl(stringUrl);
String json = "";
try{
json = NetworkUtilities.httpRequest(url);
List<String> articles = NetworkUtilities.extractFromJson(json);
return articles;
}catch (Exception e){
e.printStackTrace();
Log.v(TAG, "Problem retrieving data");
return null;
}
}
#Override
protected void onPostExecute(List<String> strings) {
if(strings != null){
mNewsAdapter.setNewsData(strings);
}
}
}
Error
W/Zygote: Unable to open libbeluga.so: dlopen failed: library "libbeluga.so" not found.
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
W/xample.newsfee: Accessing hidden method Landroid/view/View; >computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/xample.newsfee: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
com.example.newsfeed V/NetworkUtilities: Problem retrieving the json result
java.io.IOException: Cleartext HTTP traffic to api.mediastack.com not permitted
at com.android.okhttp.HttpHandler$CleartextURLFilter.checkURLPermitted(HttpHandler.java:127)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:462)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:131)
at com.example.newsfeed.Utils.NetworkUtilities.httpRequest(NetworkUtilities.java:49)
at com.example.newsfeed.MainActivity$FetchNewsArticle.doInBackground(MainActivity.java:46)
at com.example.newsfeed.MainActivity$FetchNewsArticle.doInBackground(MainActivity.java:38)
at android.os.AsyncTask$3.call(AsyncTask.java:394)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:305)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:923)
2021-03-11 22:53:28.124 9391-9391/com.example.newsfeed W/Looper: PerfMonitor looperActivity : package=com.example.newsfeed/.MainActivity time=1ms latency=447ms running=2ms procState=2 ClientTransaction{ callbacks=[android.app.servertransaction.TopResumedActivityChangeItem] } historyMsgCount=4 (msgIndex=3 wall=87ms seq=3 running=50ms runnable=28ms io=2ms late=6ms h=android.app.ActivityThread$H w=110) (msgIndex=4 wall=356ms seq=4 running=212ms runnable=80ms io=11ms late=91ms h=android.app.ActivityThread$H w=159)
2021-03-11 22:53:28.199 9391-9429/com.example.newsfeed I/AdrenoGLES-0: QUALCOMM build : 979eaa0, I11632bc865
Build Date : 11/18/20
OpenGL ES Shader Compiler Version: EV031.32.02.00
Local Branch :
Remote Branch : refs/tags/AU_LINUX_ANDROID_LA.UM.9.1.R1.11.00.00.604.067
Remote Branch : NONE
Reconstruct Branch : NOTHING
2021-03-11 22:53:28.199 9391-9429/com.example.newsfeed I/AdrenoGLES-0: Build Config : S P 10.0.6 AArch64
2021-03-11 22:53:28.199 9391-9429/com.example.newsfeed I/AdrenoGLES-0: Driver Path : /vendor/lib64/egl/libGLESv2_adreno.so
2021-03-11 22:53:28.213 9391-9429/com.example.newsfeed I/AdrenoGLES-0: PFP: 0x016ee190, ME: 0x00000000
2021-03-11 22:53:28.253 9391-9429/com.example.newsfeed E/LB: fail to open file: No such file or directory
The error seems to be: java.io.IOException: Cleartext HTTP traffic to api.mediastack.com not permitted.
Starting from Android 9, clear text http communication is disabled by default.
Check out the official Android documentation for this and also this question for further information.

org.json.JSONException: No value for opening_hours ,how to handle this type of error

logcat screenshot
**after parsing json if there is no value for opening_hours nothing is displaying how to handle that please help me.
url="https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJoTjQ-EC_wjsRjC-0kVQOIg0&key=API_KEY" **
I did all techniques but not got success in that please help me to resolve this error
public class Details extends AppCompatActivity {
private ImageView image_details, open, close;
private TextView text_mobile, openNow;
private RequestQueue mRequestQueue;
String place_id, img_url, mobile, open_now;
ArrayList<DetailsPojo> mDetailsList;
private Context mContext;
LinearLayout openingLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
findViewByIds();
mRequestQueue = VolleySingleton.getInstance().getRequestQueue();
Intent intent = getIntent();
//if (getIntent().hasExtra("PLACE_ID"))
place_id = intent.getStringExtra("PLACE_ID");
Toast.makeText(this, "Place ID :" + place_id.toString(), Toast.LENGTH_SHORT).show();
parseJson();
}
private void parseJson() {
String url = "https://maps.googleapis.com/maps/api/place/details/json?placeid=" + place_id + "&key=" + KEY;
Log.d("DetailedURL",url);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject resultObject = response.getJSONObject("result");
mobile = resultObject.optString("formatted_phone_number", "not available");
if (resultObject.has("formatted_phone_number")) {
text_mobile.setText(mobile);
} else {
text_mobile.setText("not available");
}
JSONObject openingObject = resultObject.getJSONObject("opening_hours");
open_now = openingObject.optString("open_now", "Not provided");
if(resultObject.has("opening_hours")) {
if (open_now.equalsIgnoreCase("true")) {
open.setVisibility(View.VISIBLE);
openNow.setText("Open");
} else {
close.setVisibility(View.VISIBLE);
openNow.setText("Closed");
}
}else {
openNow.setText("no information provided for Open/Close");
}
if(resultObject.has("photos")){
JSONArray photosArray = resultObject.getJSONArray("photos");
for (int i = 0; i < photosArray.length(); i++) {
JSONObject photosObject = photosArray.getJSONObject(i);
img_url = URL_PHOTO + photosObject.optString("photo_reference","No image available") + "&key=" + KEY;
if (img_url.isEmpty()) {
image_details.setImageResource(R.drawable.hospital);
} else {
Picasso.with(mContext).load(img_url).fit().centerInside().into(image_details);
}
}
}else{
image_details.setImageResource(R.drawable.no_image_available);
}
// mDetailsList.add(new DetailsPojo(img_url));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mRequestQueue.add(request);
}
private void findViewByIds() {
image_details = findViewById(R.id.image_view);
open = findViewById(R.id.open);
close = findViewById(R.id.closed);
text_mobile = findViewById(R.id.text_mobile);
openNow = findViewById(R.id.text_open_now);
openingLayout=findViewById(R.id.Openinglayout);
}
}
Please check your JSON that is coming from the Google APIs https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJoTjQ-EC_wjsRjC-0kVQOIg0&key=AIzaSyBB8VIJUlcVwYC2EnEQATSMIa9S1cDguDg
as you can see in Logcat that it is saying that No value for "opening_hours".
& you are trying to get that JSONObject without checking it that it exists or not.
here you can see your code :-
JSONObject openingObject = resultObject.getJSONObject("opening_hours");
So first validate it that it is coming or not as per the documentation it can even throw the exception if the mapping does not go well.
https://developer.android.com/reference/org/json/JSONObject#getJSONObject(java.lang.String)

How to create my own arrayAdapter for listView - Android [duplicate]

This question already has answers here:
BaseAdapter class wont setAdapter inside Asynctask - Android
(4 answers)
Closed 9 years ago.
I am trying to create my own arrayAdapter so I can place multiple textviews inside of a listview. I have searched everywhere and can not find a way to do it. I am new to this and not so sure how to handle it. So far I have an asynctask that gathers 3 strings in a JSON method. These strings are what I want placed in the textViews but I have no idea how to do so, here is my current code.
class loadComments extends AsyncTask<JSONObject, String, JSONObject> {
private ArrayAdapter<String> mAdapter = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
protected JSONObject doInBackground(JSONObject... params) {
JSONObject json2 = CollectComments.collectComments(usernameforcomments, offsetNumber);
return json2;
}
#Override
protected void onPostExecute(JSONObject json2) {
try {
if (json2.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res2 = json2.getString(KEY_SUCCESS);
if(Integer.parseInt(res2) == 1){
JSONArray commentArray = json2.getJSONArray(KEY_COMMENT);
final String comments[] = new String[commentArray.length()];
for ( int i=0; i<commentArray.length(); i++ ) {
comments[i] = commentArray.getString(i);
}
JSONArray numberArray = json2.getJSONArray(KEY_NUMBER);
String numbers[] = new String[numberArray.length()];
for ( int i=0; i<numberArray.length(); i++ ) {
numbers[i] = numberArray.getString(i);
}
JSONArray usernameArray = json2.getJSONArray(KEY_USERNAME);
String usernames[] = new String[usernameArray.length()];
for ( int i=0; i<usernameArray.length(); i++ ) {
usernames[i] = usernameArray.getString(i);
}
ArrayList<String> myList = new ArrayList<String>();
class MyClassAdapter extends ArrayAdapter<String> {
private Context context;
public MyClassAdapter(Context context, int textViewResourceId, ArrayList<String> items) {
super(context, textViewResourceId, items);
this.context = context;
}
public View getView(int position, View convertView) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_item, null);
}
String item = getItem(position);
if (item!= null) {
// My layout has only one TextView
TextView commentView = (TextView) view.findViewById(R.id.listComment);
TextView usernameView = (TextView) view.findViewById(R.id.listPostedBy);
TextView NumberView = (TextView) view.findViewById(R.id.listNumber);
// do whatever you want with your string and long
commentView.setText(comments);
NumberView.setText(numbers);
usernameView.setText(usernames);
}
return view;
}
}
}//end if key is == 1
else{
// Error in registration
registerErrorMsg.setText(json2.getString(KEY_ERROR_MSG));
}//end else
}//end if
} //end try
catch (JSONException e) {
e.printStackTrace();
}//end catch
}
}
new loadComments().execute();
This code does not work but I think I am on the right track.
Let us say, you create a class that hold your information about the comments instead of creating three related Arrays :
class Commentary
{
public String username;
public String comment;
public int commentaryIndex;
}
The BaseAdapter can take a List as a parameter whereas the ArrayAdapter wouldn't.
class MyRealAdapter extends BaseAdapter
{
private List<Commentary> comments;
public MyRealAdapter(List<Commentary> comments )
{
this.comments = comments;
}
#Override
public int getCount() {
return comments.size();
}
#Override
public Object getItem(int index) {
return comments.get(index);
}
#Override
public long getItemId(int index) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Commentary c = (Commentary) getItem(position);
//c.username, c.comment, c.commentaryIndex
// create the view and stuff
return null;
}
}
As you can see, you again have the getView method but now you can retrieve your complete objet and not just a String.
There is a couple more method to override, but as you can see it's very simple.
You might need to pass other argument like a Context or a LayoutInflater to the constructor, but it's not mandatory.
EDIt :
JSONArray commentArray = json2.getJSONArray(KEY_COMMENT);
JSONArray numberArray = json2.getJSONArray(KEY_NUMBER);
JSONArray usernameArray = json2.getJSONArray(KEY_USERNAME);
ArrayList<Commentary> comments = new ArrayList<commentary>();
for ( int i=0; i<commentArray.length(); i++ ) {
Commentary c = new Commentary();
c.username = usernameArray.getString(i);
c.comment = commentArray.getString(i);
c.commentaryIndex = Integer.parseInt(numberArray.getString(i));
comments.add(c);
}
MyRealAdapter adapter = new MyRealAdapter(comments);

Android Fragment : replace Crash and Hide/show don't works

I'm making an App that implements this slide-out Menu and i'm pretty much satisfied about the implementation.
I divided my app in multiple Fragment for one Activity so for each section of the menu there is a Fragment.
The point is that i have an OnItemClickListener that allow me to switch beetween Fragments, so I'd tried two methods :
replace() : it works fine for all fragment except for one of them that load a XML which contains a map (code below). On first load there's no problem but when I switch to another fragment and came back to the one with the map, the app crash.
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
<RelativeLayout
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageButton
android:id="#+id/refreshButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="63dp"
android:src="#drawable/refresh"
android:text="Rafraichir" />
</RelativeLayout>
public class MapFragment extends Fragment implements
OnInfoWindowClickListener, LocationListener {
private GoogleMap gMap;
Geocoder geocoder;
private LocationManager locationManager;
private Location userLocation;
private String provider;
private ImageButton refreshButton;
ArrayList<Parking> Parkings;
Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragmen_map,
container, false);
gMap = ((SupportMapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
gMap.setOnInfoWindowClickListener(this);
context = getActivity();
geocoder = new Geocoder(context);
refreshButton = (ImageButton) view.findViewById(R.id.refreshButton);
refreshButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getParkingsConnection = new GetParkingsConnection(context);
getParkingsConnection.execute(null, null, null);
myParkings = new ArrayList<Parking>();
}
});
// Geolocaliation
LocationManager service = (LocationManager) getActivity()
.getSystemService(getActivity().LOCATION_SERVICE);
boolean enabled = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// Check if enabled and if not send user to the GSP settings
// Better solution would be to display a dialog and suggesting to
// go to the settings
if (!enabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
// Get the location manager
locationManager = (LocationManager) getActivity().getSystemService(
getActivity().LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
return view;
}
private Double[] getLatAndLong(String addresse) {
List<Address> addresses = null;
Double latALng[] = new Double[2];
try {
addresses = geocoder.getFromLocationName(addresse, 1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (addresses.size() > 0) {
double latitude = addresses.get(0).getLatitude();
double longitude = addresses.get(0).getLongitude();
latALng[0] = latitude;
latALng[1] = longitude;
}
return latALng;
}
private GetParkingsConnection getParkingsConnection;
JSONObject json;
// Non-Statice inner class : connection au serveur
private class GetParkingsConnection extends AsyncTask<String, Void, String> {
Context mContext;
private ProgressDialog mDialog;
GetParkingsConnection(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mDialog = new ProgressDialog(mContext);
mDialog.setMessage("Mise à jour de la carte...");
mDialog.show();
}
#Override
protected String doInBackground(String... urls) {
String resultat;
resultat = getParkings();
return resultat;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("JSON", result);
JSONArray jArray;
try {
json = new JSONObject(result);
jArray = json.getJSONArray("parking");
System.out.println("*****Parkings*****" + jArray.length());
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Log.d("adresse :",
json_data.getString("adresse") + ", nom :"
+ json_data.getString("nom")
+ ", latitude :"
+ json_data.getDouble("latitude")
+ ", longitude :"
+ json_data.getDouble("longitude"));
String adresse = json_data.getString("adresse");
Double latALng[] = getLatAndLong(adresse);
Double lat = latALng[0]; // json_data.getDouble("latitude");
Double lng = latALng[1]; // json_data.getDouble("longitude");
String nom = json_data.getString("nom");
LatLng parkingLocation = new LatLng(lat, lng);
Marker parking = gMap.addMarker(new MarkerOptions()
.position(parkingLocation)
.title(nom)
.snippet(adresse)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.my_marker)));
Parking park = new Parking(parking.getId(), adresse, nom,
"", lat, lng);
myParkings.add(park);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mDialog.dismiss();
}
// Fonction effectuant uenrequête de type GET sur le fichier
// getParking.php
protected String getParkings() {
HttpResponse response = null;
String res = "";
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
// request.setURI(new
// URI("http://pkdom.1x.biz/getParkings.php"));
request.setURI(new URI(
"http://glennsonna.fr/webService/getParkings"));
response = client.execute(request);
HttpEntity entity = response.getEntity();
// JSONObject json = new JSONObject();
res = EntityUtils.toString(entity);
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res;
}
}
#Override
public void onInfoWindowClick(Marker marker) {
// TODO Auto-generated method stub
Parking parkingToSend = null;
// TOAST
/*
* int p = 0;
*
* while(myParkings.get(p).idMarker != marker.getId() && p <
* myParkings.size()){ Log.d("Marker :" + marker.getId(),
* myParkings.get(p).idMarker);
*
* if(myParkings.get(p).idMarker.equals(marker.getId()) ){
* parkingToSend = myParkings.get(p); Context context =
* getApplicationContext(); CharSequence text = "Match" +
* parkingToSend.adresse; int duration = Toast.LENGTH_SHORT; Toast toast
* = Toast.makeText(context, text, duration); toast.show(); }
*
* p++; }
*/
for (int p = 0; p < myParkings.size(); p++) {
Log.d("Marker :" + marker.getId(), myParkings.get(p).idMarker);
if (myParkings.get(p).idMarker.equals(marker.getId())) {
parkingToSend = myParkings.get(p);
}
}
if (parkingToSend != null) {
Intent i = new Intent(context.getApplicationContext(),
ParkingDetail.class);
i.putExtra("id", parkingToSend.idMarker);
i.putExtra("adresse", parkingToSend.adresse);
i.putExtra("nom", parkingToSend.nom);
i.putExtra("descri", parkingToSend.description);
i.putExtra("latitude", parkingToSend.lat);
i.putExtra("longitude", parkingToSend.lng);
startActivity(i);
}
}
#Override
public void onLocationChanged(Location user) {
// TODO Auto-generated method stub
Log.d("Latitude", ":" + user.getLatitude());
Log.d("Longitude", ":" + user.getLongitude());
this.gMap.setMyLocationEnabled(true);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
hide() & show() : I can switch beetween fragment but excepted for the first screen (the map) all the other show a blank screen without content.
private MenuDrawer mMenuDrawer;
private MenuAdapter mAdapter;
private ListView mList;
private GoogleMap gMap;
private int mActivePosition = -1;
List<Object> mmyFragment;
Fragment currentFragment;
myMapFragment mmyMapFragment;
myMonCompteFragment mmyMonCompteFragment;
myPaiementFragment mmyPaiementFragment;
myReservationsFragment mmyReservationsFragment;
myFavorisFragment mmyFavorisFragment;
myCodePromoFragment mmyCodePromoFragment;
myAboutFragment mmyAboutFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_my_map);
ActionBar actionBar = this.getActionBar();
actionBar.setSubtitle("Trouvez votre parking");
actionBar.setTitle("my");
actionBar.setDisplayHomeAsUpEnabled(true);
setupMenu();
setupFragments();
}
private void setupMenu() {
mMenuDrawer = MenuDrawer.attach(this, Position.LEFT);
mMenuDrawer.setContentView(R.layout.activity_my_map);
List<Object> items = new ArrayList<Object>();
items.add(new Item("Carte", R.drawable.ic_action_refresh_dark));
items.add(new Item("Mon Compte", R.drawable.ic_action_refresh_dark));
items.add(new Item("Paiement", R.drawable.ic_action_select_all_dark));
items.add(new Item("Mes Réservations",
R.drawable.ic_action_select_all_dark));
items.add(new Item("Mes favoris", R.drawable.ic_action_refresh_dark));
// items.add(new Category(" "));
items.add(new Item("Code Promo", R.drawable.ic_action_refresh_dark));
items.add(new Item("A propos", R.drawable.ic_action_select_all_dark));
// A custom ListView is needed so the drawer can be notified when it's
// scrolled. This is to update the position
// of the arrow indicator.
mList = new ListView(this);
mAdapter = new MenuAdapter(items);
mList.setAdapter(mAdapter);
mList.setOnItemClickListener(mItemClickListener);
mMenuDrawer.setMenuView(mList);
}
private void setupFragments() {
mmyMapFragment = new myMapFragment();
mmyMonCompteFragment = new myMonCompteFragment();
mmyPaiementFragment = new myPaiementFragment();
mmyReservationsFragment = new myReservationsFragment();
mmyFavorisFragment = new myFavorisFragment();
mmyCodePromoFragment = new myCodePromoFragment();
mmyAboutFragment = new myAboutFragment();
mmyFragment = new ArrayList<Object>();
mmyFragment.add(mmyMapFragment);
mmyFragment.add(mmyMonCompteFragment);
mmyFragment.add(mmyPaiementFragment);
mmyFragment.add(mmyReservationsFragment);
mmyFragment.add(mmyFavorisFragment);
mmyFragment.add(mmyCodePromoFragment);
mmyFragment.add(mmyAboutFragment);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.replace(R.id.myContenu, mmyMapFragment);
fragmentTransaction.commit();
currentFragment = mmyMapFragment;
}
private AdapterView.OnItemClickListener mItemClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
mActivePosition = position;
mMenuDrawer.setActiveView(view, position);
mMenuDrawer.closeMenu();
if ((mmyFragment.get(position) != null)
/*&& (mmyFragment.get(position).getClass() != currentFragment
.getClass())*/) {
Fragment nexFragment = (Fragment) mmyFragment
.get(position);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.hide(currentFragment);
if (!nexFragment.isHidden()) {
//fragmentTransaction.add(nexFragment, nexFragment.getTag());
Toast.makeText(
getApplicationContext(),
""
+ nexFragment.getClass().toString()
+ " : "
+ mmyFragment.indexOf(mmyFragment
.get(position)), Toast.LENGTH_SHORT).show();
}
//fragmentTransaction.addToBackStack(nexFragment.getTag());
fragmentTransaction.attach(nexFragment);
fragmentTransaction.replace(R.id.myContenu, nexFragment);
//fragmentTransaction.show(nexFragment);
currentFragment = nexFragment;
fragmentTransaction.commit();...}
After one day i finaly found the answer here
So i just implemented the code below. But I have to use replace(); so I'll find a way to save my map state.
public void onDestroyView ()
{
try{
SupportMapFragment fragment = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map));
FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
}catch(Exception e){
}
super.onDestroyView();
}

HTTP POST does not return expected JSON response

I have pasted a code snippet for HTTP Post where I am POSTING a multipart message to the server which needs Authentication. I am expecting a JSON response, but when I run this I always get the login page in HTML.
public final class MyScreen extends MainScreen {
private RichTextField _Output;
public MyScreen() {
// Set the displayed title of the screen
setTitle("MyTitle");
_Output = new RichTextField();
add(_Output);
addMenuItem(_GetDataAction);
}
protected MenuItem _GetDataAction = new MenuItem("GetData", 100000, 10) {
public void run() {
String URL = "<Sample URL Goes Here>";
ServiceRequestThread svc = new ServiceRequestThread(URL,
(MyScreen) UiApplication.getUiApplication()
.getActiveScreen());
svc.start();
}
};
public void updateDestination(final String text) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
_Output.setText(text);
}
});
}
}
class ServiceRequestThread extends Thread {
protected String _URL;
protected MyScreen _Dest = null;
protected URLEncodedPostData _PostData = null;
StringBuffer writer = new StringBuffer();
public void setPOSTData(URLEncodedPostData data) {
_PostData = data;
}
public ServiceRequestThread(String URL, MyScreen screen) {
super();
_Dest = screen;
_URL = URL;
}
public void run() {
try
{
String boundary = "SATBA";
String twoHyphens = "--";
String data1 = "{\"IMPORTING\":{ \"IN_COUNTRY_CODE\":\"US\"}}";
String CRLF = "\r\n";
byte[] encoded = Base64OutputStream.encode
("User:password".getBytes(), 0, "User:password".length(), false,false);
"Prepare the data for post"
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"param\"").append(
CRLF);
writer.append("Content-Type: text/json; charset=" + "UTF-8").append(CRLF);
writer.append("Content-Transfer-Encoding: 8bit").append(CRLF);
writer.append("Request-Id:Abcd123456" ).append(CRLF);
writer.append("Request-Type:rfc_json").append(CRLF);
writer.append("function:00163E0136C01EE0AE8B059433A71727")
.append(CRLF);
writer.append(CRLF);
writer.append(data1).append(CRLF);
writer.append("--" + boundary + "--").append(CRLF);
String string = new String(writer);
HttpConnection conn1 = (HttpConnection)Connector.open(_URL,Connector.READ_WRITE);
conn1.setRequestMethod(HttpConnection.POST);
conn1.setRequestProperty("Authorization", "Basic "+ new String(encoded));
conn1.setRequestProperty("Content-Type","multipart/mixed; boundary=" + boundary);
OutputStreamWriter osw = new OutputStreamWriter(conn1.openOutputStream(), "UTF-8");
osw.write(string);
osw.flush();
osw.close();
int responseCode = conn1.getResponseCode();
if (responseCode == HttpConnection.HTTP_OK) {
InputStream data = conn1.openInputStream();
StringBuffer raw = new StringBuffer();
byte[] buf = new byte[4096];
int nRead = data.read(buf);
while (nRead > 0) {
raw.append(new String(buf, 0, nRead));
nRead = data.read(buf);
}
_Dest.updateDestination(raw.toString());
} else {
_Dest.updateDestination("responseCode="
+ Integer.toString(responseCode));
}
}
catch( IOException e)
{
e.printStackTrace();
_Dest.updateDestination("Exception:"+e.toString());
}
}
}
Turns out the code was perfectly alright and the issue was on the rim.public property file where the application.handler.http.AuthenticationSupport was set to true and because of this it was not loggging in.
Now I set it to false and get the correct response.