I am having trouble trying to get my andoid app to return a list view of all search results returned from a PHP files. I am using a wamp server to host the php files then I call them in the application using Volley. My problem is I can't get it to work with multiple return values. I have tried many different ways using videos online and resources from this site but i cant seem to get to work. This is my first Android application so I am new enough of the idea of a list view and json.
package com.example.mullally.newloginregister;
import android.app.AlertDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class HomeScreen extends AppCompatActivity {
String status = "";
ArrayAdapter<String> adapter;
ArrayList<String> items;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
final TextView createLink = (TextView) findViewById(R.id.tvCreate);
final TextView lostLink = (TextView) findViewById(R.id.tvLost);
final TextView foundLink = (TextView) findViewById(R.id.tvFound);
final Button btTest = (Button) findViewById(R.id.btTest);
createLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(HomeScreen.this, CreateAdvert.class);
HomeScreen.this.startActivity(registerIntent);
}
});
lostLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
status="Lost";
// Response received from the server
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String title = jsonResponse.getString("title");
String location = jsonResponse.getString("location");
Intent intent = new Intent(HomeScreen.this, BrowseLost.class);
intent.putExtra("title", title);
intent.putExtra("location", location);
HomeScreen.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(HomeScreen.this);
builder.setMessage("Something Went Wrong")
.setNegativeButton("Back", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
BrowseRequest browseRequest = new BrowseRequest(status, responseListener);
RequestQueue queue = Volley.newRequestQueue(HomeScreen.this);
queue.add(browseRequest);
}
});
foundLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
status = "Found";
// Response received from the server
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String title = jsonResponse.getString("title");
String location = jsonResponse.getString("location");
Intent intent = new Intent(HomeScreen.this, BrowseFound.class);
intent.putExtra("title", title);
intent.putExtra("location", location);
HomeScreen.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(HomeScreen.this);
builder.setMessage("Something Went Wrong")
.setNegativeButton("Back", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
BrowseRequest browseRequest = new BrowseRequest(status, responseListener);
RequestQueue queue = Volley.newRequestQueue(HomeScreen.this);
queue.add(browseRequest);
}
});
btTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
status = "Found";
// Response received from the server
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String title = jsonResponse.getString("title");
String description = jsonResponse.getString("description");
String location = jsonResponse.getString("location");
String status = jsonResponse.getString("status");
String category = jsonResponse.getString("category");
Intent intent = new Intent(HomeScreen.this, ViewAdvert.class);
intent.putExtra("title", title);
intent.putExtra("description", description);
intent.putExtra("location", location);
intent.putExtra("status", status);
intent.putExtra("category", category);
HomeScreen.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(HomeScreen.this);
builder.setMessage("Something Went Wrong")
.setNegativeButton("Back", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
ViewRequest viewRequest = new ViewRequest(status, responseListener);
RequestQueue queue = Volley.newRequestQueue(HomeScreen.this);
queue.add(viewRequest);
}
});
This is the home screen. When a textview is clicked it would launch a request using volley in a seperate request class it is supposed to then return values add them to a json response opject and pass them into the Browse Lost class where it is then added to a listView.
This is the Request class:
package com.example.mullally.newloginregister;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import java.util.HashMap;
import java.util.Map;
/**
* Created by mullally on 14/04/2016.
*/
public class BrowseRequest extends StringRequest {
//192.168.11.2
private static final String BROWSE_REQUEST_URL = "http://192.168.11.5/android_content/GetAdvert.php";
private Map<String,String> params;
public BrowseRequest(String status, Response.Listener<String> listener){
super(Request.Method.POST, BROWSE_REQUEST_URL,listener, null);
params=new HashMap<>();
params.put("status", status);
}
#Override
public Map<String, String> getParams() {
return params;
}
}
And this is the activity that is launched to display the list :
package com.example.mullally.newloginregister;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class BrowseLost extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_browse_lost);
final ListView listView = (ListView) findViewById(R.id.listView);
final Intent intent= getIntent();
String title = intent.getStringExtra("title");
String location = intent.getStringExtra("location");
String details = title + " Location: " + location;
List<String> foundArray = new ArrayList<>();
foundArray.add(details);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_activated_2, android.R.id.text1, foundArray);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText(getApplicationContext(),
"Position :" + itemPosition + " ListItem : " + itemValue, Toast.LENGTH_LONG)
.show();
}
});
}
}
So basically I am trying to populate the listview with all values returned from the PHP. The php encodes the values into a json response eg.
[{"title":"Phone Found","location":"Dublin 6"},{"title":"test","location":"Dublin"},{"title":"dog","location":"Dublin 1"},{"title":"new","location":"Dublin 6W"}]
Related
I have created a project in which I am using spinner.
In spinner I am setting data fetched from MySql database. The data is being fetched properly as I can get the whole in the dropdown.
The problem is that spinner is not showing the selected value in the text area.
When I tested it with another arraylist of strings which was created in the program it was working.
I don't know why it is not working properly with the data fetched from database.
Kindly help me if you know the solution.
The java file is here when I used the data from MySql database
package com.help.adminpasskart;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class addSubCategory extends AppCompatActivity {
ImageView categoryImageView , categoryImageBtn;
TextView categoryNameView ;
Button confirmBtn;
String categoryimg;
Spinner genderDrop , categoryDrop;
ArrayList<String> genders = new ArrayList<>();
ArrayList<String> words = new ArrayList<>();
private final String url = "http://passkart.online/Z_addCategory.php";
private final String url2 = "http://passkart.online/Z_getGender.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_sub_category);
categoryImageView = findViewById(R.id.addcategoryimageView);
categoryImageBtn = findViewById(R.id.addcategoryimagebtn);
categoryNameView = findViewById(R.id.addcategorynameView);
confirmBtn = findViewById(R.id.addCategoryConfirmBtn);
genderDrop = findViewById(R.id.genderDropDown);
categoryDrop = findViewById(R.id.categoryDropDown);
getGenders();
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(addSubCategory.this,
R.layout.droptextlayout,genders);
myAdapter.notifyDataSetChanged();
genderDrop.setAdapter(myAdapter);
genderDrop.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long
id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "Selected: " + item,
Toast.LENGTH_LONG).show();
genderDrop.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void getGenders(){
StringRequest request = new StringRequest(Request.Method.POST, url2, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject Jobject = new
JSONObject(response.substring(response.indexOf("{"), response.lastIndexOf("}") + 1));
String success = Jobject.getString("success");
JSONArray Jarray = Jobject.getJSONArray("datas");
if(success.equals("1")) {
for (int i = 0; i < Jarray.length(); i++) {
JSONObject object = Jarray.getJSONObject(i);
String name = object.getString("name");
genders.add(name);
}
}
} catch (JSONException jsonException) {
jsonException.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(addSubCategory.this);
queue.add(request);
};
}
The java file is here when I used the arraylist created in the program.In this code the spinner is working fine
package com.help.adminpasskart;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class addSubCategory extends AppCompatActivity {
ImageView categoryImageView , categoryImageBtn;
TextView categoryNameView ;
Button confirmBtn;
String categoryimg;
Spinner genderDrop , categoryDrop;
ArrayList<String> genders = new ArrayList<>();
ArrayList<String> words = new ArrayList<>();
private final String url = "http://passkart.online/Z_addCategory.php";
private final String url2 = "http://passkart.online/Z_getGender.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_sub_category);
categoryImageView = findViewById(R.id.addcategoryimageView);
categoryImageBtn = findViewById(R.id.addcategoryimagebtn);
categoryNameView = findViewById(R.id.addcategorynameView);
confirmBtn = findViewById(R.id.addCategoryConfirmBtn);
genderDrop = findViewById(R.id.genderDropDown);
categoryDrop = findViewById(R.id.categoryDropDown);
getGenders();
words.add("word1");
words.add("word2");
words.add("word3");
words.add("word4");
words.add("word5");
words.add("word6");
words.add("word7");
words.add("word8");
words.add("word9");
words.add("word10");
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(addSubCategory.this,
R.layout.droptextlayout,words);
myAdapter.notifyDataSetChanged();
genderDrop.setAdapter(myAdapter);
genderDrop.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long
id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "Selected: " + item,
Toast.LENGTH_LONG).show();
genderDrop.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void getGenders(){
StringRequest request = new StringRequest(Request.Method.POST, url2, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject Jobject = new
JSONObject(response.substring(response.indexOf("{"), response.lastIndexOf("}") + 1));
String success = Jobject.getString("success");
JSONArray Jarray = Jobject.getJSONArray("datas");
if(success.equals("1")) {
for (int i = 0; i < Jarray.length(); i++) {
JSONObject object = Jarray.getJSONObject(i);
String name = object.getString("name");
genders.add(name);
}
}
} catch (JSONException jsonException) {
jsonException.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(addSubCategory.this);
queue.add(request);
};
}
MySql file is here
<?php
include "config.php";
$sql="SELECT * FROM `$db`.`genderCategory`";
$result=mysqli_query($conn,$sql);
$categories['datas'] = array();
if(mysqli_num_rows($result)>0){
while($row=mysqli_fetch_array($result)){
$data['id']=$row['0'];
$data['name']= $row['1'];
$data['image']=$row['2'];
array_push($categories['datas'],$data);
}
$categories['success']='1';
echo json_encode($categories);
mysqli_close($conn);
}else{
echo "No gender added";
}
?>
Finally , I have solved it by myself
The problem was that the method getGenders() was not getting the arrayAdapter
So , I defined it inside the method and booyah !! My problem got solved .
public class addSubCategory extends AppCompatActivity {
ImageView categoryImageView , categoryImageBtn;
TextView categoryNameView ;
Button confirmBtn;
Spinner genderDrop , categoryDrop;
ArrayList<String> genders = new ArrayList<>();
ArrayAdapter<String> myAdapter;
private final String url2 = "http://passkart.online/Z_getGender.php";
String gender ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_sub_category);
categoryImageView = findViewById(R.id.addcategoryimageView);
categoryImageBtn = findViewById(R.id.addcategoryimagebtn);
categoryNameView = findViewById(R.id.addcategorynameView);
confirmBtn = findViewById(R.id.addCategoryConfirmBtn);
genderDrop = findViewById(R.id.genderDropDown);
categoryDrop = findViewById(R.id.categoryDropDown);
getGenders();
genderDrop.setOnItemSelectedListener(new
AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int
position, long id) {
myAdapter.notifyDataSetChanged();
String item = parent.getItemAtPosition(position).toString();
genderDrop.setSelection(position);
gender = item;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void getGenders(){
StringRequest request = new StringRequest(Request.Method.POST, url2,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject Jobject = new
JSONObject(response.substring(response.indexOf("{"),
response.lastIndexOf("}") + 1));
String success = Jobject.getString("success");
JSONArray Jarray = Jobject.getJSONArray("datas");
if(success.equals("1")) {
for (int i = 0; i < Jarray.length(); i++) {
JSONObject object = Jarray.getJSONObject(i);
String name = object.getString("name");
genders.add(name);
}
//Array adapter is defined here ..........
myAdapter = new ArrayAdapter<String> (addSubCategory.this, R.layout.droptextlayout,genders);
myAdapter.notifyDataSetChanged();
genderDrop.setAdapter(myAdapter);
}
} catch (JSONException jsonException) {
jsonException.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(addSubCategory.this);
queue.add(request);
};
}
I am posting this answer for those who are still dealing with this error.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm trying to delete and create a data string from a API webpage but i can't get the error code
I create API website from native php. But i create data on postman work insert and delete data
Code Delete Data
package com.dev.kedaiit.sibooks.ui.kategori;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.dev.kedaiit.sibooks.MainActivity;
import com.dev.kedaiit.sibooks.R;
import com.dev.kedaiit.sibooks.util.AppController;
import com.dev.kedaiit.sibooks.util.ServerAPI;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class DeleteKategori extends AppCompatActivity {
EditText deleteID ;
Button btnDelete;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delete_kategori);
deleteID = (EditText) findViewById(R.id.id_kategori);
btnDelete = (Button) findViewById(R.id.btn_delete);
pd = new ProgressDialog(DeleteKategori.this);
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
deleteData();
}
});
}
private void deleteData()
{
pd.setMessage("Delete Data ...");
pd.setCancelable(true);
pd.show();
StringRequest delReq = new StringRequest(Request.Method.POST, ServerAPI.URL_DELETE_KATEGORI, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pd.cancel();
Log.d("volley","response : " + response.toString());
try {
JSONObject res = new JSONObject(response);
Toast.makeText(DeleteKategori.this,"Successs" +res.getString("message"), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
startActivity(new Intent(DeleteKategori.this, KategoriFragment.class));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pd.cancel();
Log.d("volley", "error : " + error.getMessage());
Toast.makeText(DeleteKategori.this, "ERROR DELETE DATA", Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put("id_kategori",deleteID.getText().toString());
return map;
}
};
AppController.getInstance().addToRequestQueue(delReq);
}
}
Code Insert Data
package com.dev.kedaiit.sibooks.ui.kategori;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.dev.kedaiit.sibooks.R;
import com.dev.kedaiit.sibooks.util.AppController;
import com.dev.kedaiit.sibooks.util.ServerAPI;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class InsertKategori extends AppCompatActivity {
EditText id_kategori, kategori;
Button btnBatal, btnSimpan;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_kategori);
/*get data from intent*/
Intent data = getIntent();
final int update = data.getIntExtra("update",0);
String intent_idkategori = data.getStringExtra("id_kategori");
String intent_kategori = data.getStringExtra("kategori");
/*end get data from intent*/
// id_kategori = (EditText) findViewById(R.id.idkategori);
kategori = (EditText) findViewById(R.id.edt_kategori);
btnBatal = (Button) findViewById(R.id.btn_cancel);
btnSimpan = (Button) findViewById(R.id.btn_simpan);
pd = new ProgressDialog(InsertKategori.this);
/*kondisi update / insert*/
if(update == 1)
{
btnSimpan.setText("Update Data");
id_kategori.setText(intent_idkategori);
id_kategori.setVisibility(View.VISIBLE);
kategori.setText(intent_kategori);
}
btnSimpan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(update == 1)
{
Update_data();
}else {
simpanData();
}
}
});
btnBatal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent main = new Intent(InsertKategori.this,KategoriFragment.class);
startActivity(main);
}
});
}
private void Update_data()
{
pd.setMessage("Update Data");
pd.setCancelable(true);
pd.show();
StringRequest updateReq = new StringRequest(Request.Method.POST, ServerAPI.URL_UPDATE_KATEGORI,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pd.cancel();
try {
JSONObject res = new JSONObject(response);
Toast.makeText(InsertKategori.this, ""+ res.getString("message") , Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
startActivity( new Intent(InsertKategori.this,KategoriFragment.class));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pd.cancel();
Toast.makeText(InsertKategori.this, "Gagal Insert Data", Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> map = new HashMap<>();
map.put("id_kategori",id_kategori.getText().toString());
map.put("kategori",kategori.getText().toString());
return map;
}
};
AppController.getInstance().addToRequestQueue(updateReq);
}
private void simpanData()
{
pd.setMessage("Menyimpan Data");
pd.setCancelable(true);
pd.show();
StringRequest sendData = new StringRequest(Request.Method.POST, ServerAPI.URL_INSERT_KATEGORI,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pd.cancel();
try {
JSONObject res = new JSONObject(response);
Toast.makeText(InsertKategori.this, ""+ res.getString("message") , Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
startActivity( new Intent(InsertKategori.this,KategoriFragment.class));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pd.cancel();
Toast.makeText(InsertKategori.this, "Gagal Insert Data", Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> map = new HashMap<>();
map.put("id_kategori",id_kategori.getText().toString());
map.put("kategori",kategori.getText().toString());
return map;
}
};
AppController.getInstance().addToRequestQueue(sendData);
}
}
Fragment Kategori
package com.dev.kedaiit.sibooks.ui.kategori;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.dev.kedaiit.sibooks.R;
import com.dev.kedaiit.sibooks.adapter.AdapterDataKategori;
import com.dev.kedaiit.sibooks.model.DataKategori;
import com.dev.kedaiit.sibooks.util.ServerAPI;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class KategoriFragment extends Fragment {
private RecyclerView recyclerView;
private FloatingActionButton floatingActionButton;
private LinearLayoutManager linearLayoutManager;
private DividerItemDecoration dividerItemDecoration;
private List<DataKategori> list;
private RecyclerView.Adapter adapter;
public KategoriFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_kategori, container, false);
recyclerView = view.findViewById(R.id.recyclerViewKategori);
list = new ArrayList<DataKategori>();
adapter = new AdapterDataKategori(getContext(), list);
linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(), linearLayoutManager.getOrientation());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.addItemDecoration(dividerItemDecoration);
recyclerView.setAdapter(adapter);
FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab);
FloatingActionButton delKtg = (FloatingActionButton) view.findViewById(R.id.delKtg);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), InsertKategori.class);
startActivity(intent);
}
});
delKtg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(),DeleteKategori.class);
startActivity(intent);
}
});
getData();
return view;
}
private void getData() {
final ProgressDialog progressDialog = new ProgressDialog(getContext());
progressDialog.setMessage("Loading...");
progressDialog.show();
JsonObjectRequest my_request = new JsonObjectRequest(Request.Method.GET, ServerAPI.URL_DATA_KATEGORI, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try{
JSONArray jsonArray = response.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject Jobj = jsonArray.getJSONObject(i);
DataKategori obj = new DataKategori();
obj.setId_kategori(Jobj.getString("id_kategori"));
obj.setKategori(Jobj.getString("kategori"));
list.add(obj);
}
} catch (JSONException e) {
e.printStackTrace();
progressDialog.dismiss();
}
adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error: " + error.getMessage());
progressDialog.dismiss();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(my_request);
}
}
https://github.com/bellabeen/sibooks-client This project me get this in the logcat and when i dont get error code
Your code is almost fine. You just missed one thing. You did not initialize VolleyRequest. Inside simponData and UpdateData methods write this line at the bottom.
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(my_request);
instead of AppController.getInstance().addToRequestQueue(updateReq).
other thing is you are calling the fragment in intent from when response is received .You should call onbackPress() when result is recieved successfully.
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
pd.cancel();
try {
JSONObject res = new JSONObject(response);
Toast.makeText(InsertKategori.this, ""+ res.getString("message") , Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
onBackPressed();
}
},
It will restore the previous fragment. In order to update the KategoriFragment view when successful response is received, you can call the getData() method in onResume() method instead of oncreate(). it will call this method whenever fragment is visible to the use
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
My App crashes when you click on register as a new user. The source code is in online cab booking github. This app is a uber kind of app, where you can register and request for rides
I have checked my Android Manifest, everything seems to be in order.
I have tried everything, the app crashes
Register.java
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.kerisgenuine.uberclone.app.AppConfig;
import com.example.kerisgenuine.uberclone.app.AppController;
import com.example.kerisgenuine.uberclone.helper.SQLiteHandler;
import com.example.kerisgenuine.uberclone.helper.SessionManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Register extends AppCompatActivity {
private EditText inputFullName;
private EditText inputEmail;
private EditText inputContact;
private Button btnRegister;
private EditText inputPassword;
private ProgressDialog pDialog;
private Spinner spinner;
private TextView carsss;
private ArrayList<carList> carlist;
private SessionManager session;
private SQLiteHandler db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
inputFullName = (EditText) findViewById(R.id.etUsername);
inputEmail = (EditText) findViewById(R.id.etEmail);
spinner=(Spinner)findViewById(R.id.sCarSelect);
carlist = new ArrayList<carList>();
carsss=(TextView)findViewById(R.id.tvSelcar);
inputPassword = (EditText) findViewById(R.id.etPassword);
inputContact = (EditText) findViewById(R.id.etContact);
btnRegister = (Button) findViewById(R.id.btRegister);
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE| WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
Intent intent = new Intent(Register.this,
MainActivity.class);
startActivity(intent);
finish();
}
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String c=parent.getItemAtPosition(position).toString();
carsss.setText(c);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString().trim();
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
String contact = inputContact.getText().toString().trim();
String getcars = carsss.getText().toString().trim();
if (!name.isEmpty() && !email.isEmpty()&& !contact.isEmpty() && !password.isEmpty()&& !getcars.isEmpty()) {
registerUser(name, email, password, contact,getcars);
} else {
Toast.makeText(getApplicationContext(),
"Please enter your details!", Toast.LENGTH_LONG)
.show();
}
}
});
new GetCategories().execute();
}
private void populateSpinner() {
List<String> lables = new ArrayList<String>();
for (int i = 0; i < carlist.size(); i++) {
lables.add(carlist.get(i).getName());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(spinnerAdapter);
}
private class GetCategories extends AsyncTask<Void, Void, Void> {
UrlConnection conn;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
Log.d("doinbackground"," ");
String result;
conn=new UrlConnection();
InputStream os=conn.ByGetMethod("https://seely-sled.000webhostapp.com/selectCab.php");
result =conn.ConvertStramatoString(os);
if(result!=null){
try{
JSONArray categories = new JSONArray(result);
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
carList cat = new carList(catObj.getString("car_name"));
carlist.add(cat);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
populateSpinner();
super.onPostExecute(aVoid);
}
}
private void registerUser(final String name,final String email,final String password,final String contact,final String carsss) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.url_register, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(" ", "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String contact = user.getString("contact");
String cartype = user.getString("car_name");
// Inserting row in users table
db.addUser(name, email, uid, contact,cartype);
Toast.makeText(getApplicationContext(), "User successfully registered. Try login now!", Toast.LENGTH_LONG).show();
// Launch login activity
Intent intent = new Intent(
Register.this,
Login.class);
startActivity(intent);
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(" ", "error_msg" + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
params.put("email", email);
params.put("password", password);
params.put("contact", contact);
params.put("car_name", carsss);
return params;
}
};
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
logcat
06-09 04:54:31.582 3831-3902/com.example.kerisgenuine.uberclone E/LOG_TAG: Error in getDATA
06-09 04:52:20.764 3855-3855/? E/dex2oat: Failed to create oat file: /data/dalvik-cache/x86/data#app#com.example.kerisgenuine.uberclone-
1#split_lib_slice_5_apk.apk#classes.dex: Permission denied
06-09 04:50:54.309 3698-3698/? E/memtrack: Couldn't load memtrack module (No such file or directory)
06-09 04:50:54.309 3698-3698/? E/android.os.Debug: failed to load memtrack module: -2
--------- beginning of crash
06-09 04:54:31.583 3831-3902/com.example.kerisgenuine.uberclone E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.kerisgenuine.uberclone, PID: 3831
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: lock == null
at java.io.Reader.<init>(Reader.java:64)
at java.io.InputStreamReader.<init>(InputStreamReader.java:122)
at java.io.InputStreamReader.<init>(InputStreamReader.java:57)
at com.example.kerisgenuine.uberclone.UrlConnection.ConvertStramatoString(UrlConnection.java:118)
at com.example.kerisgenuine.uberclone.Register$GetCategories.doInBackground(Register.java:142)
at com.example.kerisgenuine.uberclone.Register$GetCategories.doInBackground(Register.java:128)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
you should return the result in doInBackground() and use the result in your on postExecute() :
private class GetCategories extends AsyncTask<String, String, String> {
UrlConnection conn;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
Log.d("doinbackground"," ");
String result;
conn=new UrlConnection();
InputStream os=conn.ByGetMethod("https://seely-sled.000webhostapp.com/selectCab.php");
result =conn.ConvertStramatoString(os);
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(aVoid);
try{
JSONArray categories = new JSONArray(result);
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
carList cat = new carList(catObj.getString("car_name"));
carlist.add(cat);
}
populateSpinner();
} catch (JSONException e) {
e.printStackTrace();
}
}
In this android code it is sending description in database but not sending Spinner value in database
package com.example.mis_internee.test;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.sql.SQLOutput;
import java.util.HashMap;
import java.util.Map;
public class atd_leave_form extends AppCompatActivity {
EditText Descr, lastname, age;
Button insert;
TextView back;
RequestQueue requestQueue;
String insertUrl = "http://192.168.0.102/A/issue.php";
// String showUrl = "http://192.168.1.65/tutorial/showStudents.php";
TextView TV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_atd_leave_form);
Descr = (EditText) findViewById(R.id.descText);
insert = (Button) findViewById(R.id.send);
TV = (TextView) findViewById(R.id.uname);
back = (TextView) findViewById(R.id.Back);
// TV= (TextView)findViewById(R.id.textView);
final Spinner staticSpinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> staticAdapter = ArrayAdapter.createFromResource(this, R.array.list,android.R.layout.simple_spinner_item);
staticAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
staticSpinner.setAdapter(staticAdapter);
// String name= "Username= "+getIntent().getExtras().getString("username");
// TV.setText(name);
// String name= "Username= "+getIntent().getExtras().getString("username");
// result.setText(name);
//
// back.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// Intent i = new Intent(atd_leave_form.this, MainActivity.class);
// startActivity(i);
//
//
// }
// });
requestQueue = Volley.newRequestQueue(getApplicationContext());
insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String DESCR = Descr.getText().toString();
final String Spin = staticSpinner.getSelectedItem().toString();
StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(Descr.getText().toString().equals("")){
Toast.makeText(getApplication(),"Please Enter Detail ",Toast.LENGTH_LONG).show();
}
else if(Descr.getText().toString().length()<10){
Toast.makeText(getApplication(),"Text Must be Greater Than 10",Toast.LENGTH_LONG).show();
}
else{
System.out.println(response.toString());
Toast.makeText(getApplication(),"Application Submitted Successfully....!",Toast.LENGTH_LONG).show();
Intent intent = new Intent(atd_leave_form. this, Issue.class);
startActivity(intent);
}
}}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> parameters = new HashMap<String, String>();
parameters.put("Descr",Descr.getText().toString());
parameters.put("Spin",staticSpinner.toString());
return parameters;
}
};
requestQueue.add(request);
}
});
}
}
i used spinner and select value and submit it but no error with submission description in database. i am using oracle web services with wamp server, but description submitting spinner value is not.
thanks in advance
use staticSpinner.getSelectedItem().toString() instead of staticSpinner.toString() in posting parameters
you are posting wrong data check below code
insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String DESCR = Descr.getText().toString();
final String Spin = staticSpinner.getSelectedItem().toString();
StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(Descr.getText().toString().equals("")){
Toast.makeText(getApplication(),"Please Enter Detail ",Toast.LENGTH_LONG).show();
}
else if(Descr.getText().toString().length()<10){
Toast.makeText(getApplication(),"Text Must be Greater Than 10",Toast.LENGTH_LONG).show();
}
else{
System.out.println(response.toString());
Toast.makeText(getApplication(),"Application Submitted Successfully....!",Toast.LENGTH_LONG).show();
Intent intent = new Intent(atd_leave_form. this, Issue.class);
startActivity(intent);
}
}}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> parameters = new HashMap<String, String>();
parameters.put("Descr",Descr.getText().toString());
parameters.put("Spin",Spin);//change here
return parameters;
}
};
requestQueue.add(request);
}
});
}
}
Below I've listed my activity code, call out to the web service, and the json parsing class I created to parse the web service results. I'm trying to pass a user object back to the activity to determine what they can/can't do, however, I'm not getting past the "after execute" log statement. onRequestFinished never gets called which is where I would have expected it to end up. Any help would be greatly appreciated as there doesn't seem to be much activity with DataDroid...
LoginActivity.java
package com.motosho.ui;
import com.foxykeep.datadroid.requestmanager.Request;
import com.foxykeep.datadroid.requestmanager.RequestManager.RequestListener;
import com.motosho.R;
import com.motosho.data.model.User;
import com.motosho.data.requestmanager.RequestFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.content.Intent;
public final class LoginActivity extends DataDroidActivity implements RequestListener,
OnClickListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
bindViews();
}
protected void onResume() {
super.onResume();
for(int i=0; i < mRequestList.size(); i++) {
Request request = mRequestList.get(i);
if(mRequestManager.isRequestInProgress(request)) {
mRequestManager.addRequestListener(this, request);
setProgressBarIndeterminateVisibility(true);
} else {
mRequestManager.callListenerWithCachedData(this, request);
i--;
mRequestList.remove(request);
}
}
}
protected void onPause() {
super.onPause();
if(!mRequestList.isEmpty()) {
mRequestManager.removeRequestListener(this);
}
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
private void bindViews() {
((Button) findViewById(R.id.sign_in_button)).setOnClickListener(this);
}
private void callLoginWS(String username, String pin, String eventId) {
Log.i("LOGIN", "in callLoginWS - username=" + username + ", pin=" + pin + ", eventid=" + eventId);
setProgressBarIndeterminateVisibility(true);
Request request = RequestFactory.getLoginRequest(username, pin, eventId);
mRequestManager.execute(request, this);
Log.i("LOGIN", "after execute");
mRequestList.add(request);
}
public void onClick(View view) {
switch(view.getId()) {
case R.id.sign_in_button:
EditText emailText = (EditText) findViewById(R.id.email);
EditText pinText = (EditText) findViewById(R.id.pin);
Log.i("LOGIN","set email and pin text");
callLoginWS(emailText.getText().toString(), pinText.getText().toString(),"9");
break;
}
}
#Override
public void onRequestFinished(Request request, Bundle resultData) {
Log.i("LOGIN", "inside onRequestFinished");
if(mRequestList.contains(request)) {
setProgressBarIndeterminateVisibility(false);
Log.i("LOGIN", "request found");
mRequestList.remove(request);
Toast toast = Toast.makeText(this, "request finished", Toast.LENGTH_SHORT);
toast.show();
User user = resultData.getParcelable("user");
if(user != null) {
startActivity(new Intent(this, MainActivity.class).putExtras(resultData));
}
}
}
#Override
public void onRequestConnectionError(Request request, int statusCode) {
Log.i("LOGIN", "onRequestConnectionError");
if(mRequestList.contains(request)) {
setProgressBarIndeterminateVisibility(false);
//show error
Toast toast = Toast.makeText(this, "connection error", Toast.LENGTH_SHORT);
toast.show();
mRequestList.remove(request);
}
}
#Override
public void onRequestDataError(Request request) {
Log.i("LOGIN", "onRequestDataError");
if(mRequestList.contains(request)) {
setProgressBarIndeterminateVisibility(false);
mRequestList.remove(request);
//show error
Toast toast = Toast.makeText(this, "data error", Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
public void onRequestCustomError(Request request, Bundle resultData) {
// Never called
}
public void connectionErrorDialogRetry(Request request) {
Log.i("LOGIN", "connectionErrorDialogRetry");
String username = request.getString("username");
String pin = request.getString("pin");
String eventId = request.getString("eventid");
callLoginWS(username,pin,eventId);
}
}
LoginOperation.java
package com.motosho.data.operation;
import java.util.HashMap;
import android.content.Context;
import android.os.Bundle;
import com.foxykeep.datadroid.exception.ConnectionException;
import com.foxykeep.datadroid.exception.CustomRequestException;
import com.foxykeep.datadroid.exception.DataException;
import com.foxykeep.datadroid.network.NetworkConnection;
import com.foxykeep.datadroid.network.NetworkConnection.ConnectionResult;
import com.foxykeep.datadroid.network.NetworkConnection.Method;
import com.foxykeep.datadroid.requestmanager.Request;
import com.foxykeep.datadroid.service.RequestService.Operation;
import com.motosho.config.WSConfig;
import com.motosho.data.factory.LoginJsonFactory;
public final class LoginOperation implements Operation {
#Override
public Bundle execute(Context context, Request request)
throws ConnectionException, DataException, CustomRequestException {
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", request.getString("username"));
params.put("pin", request.getString("pin"));
params.put("eventid", request.getString("eventid"));
NetworkConnection networkConnection = new NetworkConnection(context, WSConfig.WS_LOGIN_URL);
networkConnection.setMethod(Method.POST);
networkConnection.setParameters(params);
ConnectionResult result = networkConnection.execute();
return LoginJsonFactory.parseResult(result.body);
}
}
LoginJsonFactory.java
package com.motosho.data.factory;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.util.Log;
import com.foxykeep.datadroid.exception.DataException;
import com.motosho.config.JSONTag;
import com.motosho.data.model.User;
public final class LoginJsonFactory {
private static final String TAG = LoginJsonFactory.class.getName();
private LoginJsonFactory() { }
#SuppressWarnings("null")
public static Bundle parseResult(String wsResponse) throws DataException {
User user = new User();
try {
JSONObject parser = new JSONObject(wsResponse);
JSONObject jsonRoot = parser.getJSONObject(JSONTag.USER_ELEM);
user.firstName = jsonRoot.getString(JSONTag.USER_ELEM_FIRST_NAME);
user.lastName = jsonRoot.getString(JSONTag.USER_ELEM_LAST_NAME);
user.phoneNumber = jsonRoot.getString(JSONTag.USER_ELEM_PHONE_NUMBER);
user.role = jsonRoot.getString(JSONTag.USER_ELEM_ROLE);
JSONArray jsonPositionsArray = jsonRoot.getJSONArray(JSONTag.USER_ELEM_LIST_POSITIONS);
int size = jsonPositionsArray.length();
List<String> tempPositionsArray = null;
for (int i=0; i < size; i++) {
tempPositionsArray.add(jsonPositionsArray.getString(i));
}
user.positions = tempPositionsArray;
JSONArray jsonCapabilitiesArray = jsonRoot.getJSONArray(JSONTag.USER_ELEM_LIST_CAPABILITIES);
size = jsonCapabilitiesArray.length();
List<String> tempCapabilitiesArray = null;
for(int i=0; i < size; i++) {
tempCapabilitiesArray.add(jsonCapabilitiesArray.getString(i));
}
user.capabilities = tempCapabilitiesArray;
} catch (JSONException e) {
Log.e(TAG, "JSONException", e);
throw new DataException(e);
}
Bundle bundle = new Bundle();
bundle.putParcelable("user", user);
return bundle;
}
}