I have searched all over for a good code for uploading an mp3 or similar file to a php server and have tested over 10 samples but none has been successful so far. Most codes I have checked out are either full of bugs or use outdated libraries.
I would appreciate if anyone has a truly working code sample. Possibly one that uses volley or a similar library. Would appreciate any help or some code that points me in the right direction.
Thanks
You can use loopj Android Asynchronous Http Client lib for uploading file to the php server.
download the lib file from given link and put into your project's libs folder and use this code for uploading file.
public void postFile(){
RequestParams params = new RequestParams();
params.put("fileTitle","MyFile1");
params.put("file", new File("File Path Here")); // e.g Environment.getExternalStorageDirectory().getPath() + "/test.mp3"
AsyncHttpClient client = new AsyncHttpClient();
client.post("http://www.yourweserviceurlhere.com", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
// TODO Auto-generated method stub
}
#Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
// TODO Auto-generated method stub
}
});
}
if you want progress of uploading. then you can use my custom design class. for this also require common io 2.4 lib reference in converting HTTPresponse into string.
public class AsyncLoader {
private String url;
private LoaderCallBackHandler mCallback;
private Context mContext;
private RequestParams params;
private RequestHandle handle;
public interface LoaderCallBackHandler {
public void onStartUploading();
public void uploadComplete(String response);
public void failedWithError(Throwable error);
public void progressUpdate(long bytesWritten, long bytesTotal);
public void onCancle();
public void onFinish();
}
public AsyncLoader(Context mContext,String url,RequestParams params, LoaderCallBackHandler callback) {
this.mContext = mContext;
this.url = url;
this.params = params;
this.mCallback = callback;
}
public void startTransfer() {
AsynchConfig.mClient.setTimeout(50000);
handle = AsynchConfig.mClient.post(mContext, url, params,handlerInterface);
}
private ResponseHandlerInterface handlerInterface = new ResponseHandlerInterface() {
#Override
public void sendStartMessage() {
if(mCallback != null) {
mCallback.onStartUploading();
}
}
#Override
public void sendResponseMessage(HttpResponse response) throws IOException {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
// TODO convert in stream to JSONObject and do whatever you need to
StringWriter writer = new StringWriter();
IOUtils.copy(instream, writer, Charset.defaultCharset());
String theString = writer.toString();
if(mCallback != null) {
mCallback.uploadComplete(theString);
}
}
}
#Override
public void sendSuccessMessage(int arg0, org.apache.http.Header[] arg1, byte[] arg2) {
}
#Override
public void sendFailureMessage(int arg0, org.apache.http.Header[] arg1,
byte[] arg2, Throwable error) {
if(mCallback != null) {
mCallback.failedWithError(error);
}
}
#Override
public void sendFinishMessage() {
if(mCallback != null) {
mCallback.onFinish();
}
}
#Override
public void sendProgressMessage(long bytesWritten, long bytesTotal) {
if(mCallback != null) {
mCallback.progressUpdate(bytesWritten, bytesTotal);
}
}
#Override
public void setUseSynchronousMode(boolean arg0) {
}
#Override
public void setRequestURI(URI arg0) {
}
#Override
public void setRequestHeaders(org.apache.http.Header[] arg0) {
}
#Override
public URI getRequestURI() {
return null;
}
#Override
public org.apache.http.Header[] getRequestHeaders() {
return null;
}
#Override
public void sendCancelMessage() {
if(mCallback != null) {
mCallback.onCancle();
mCallback.onFinish();
}
}
#Override
public void sendRetryMessage(int retryNo) {
// TODO Auto-generated method stub
}
#Override
public boolean getUseSynchronousMode() {
// TODO Auto-generated method stub
return false;
}
#Override
public void setUsePoolThread(boolean usePoolThread) {
// TODO Auto-generated method stub
}
#Override
public boolean getUsePoolThread() {
// TODO Auto-generated method stub
return false;
}
#Override
public void onPreProcessResponse(ResponseHandlerInterface instance,
HttpResponse response) {
// TODO Auto-generated method stub
}
#Override
public void onPostProcessResponse(ResponseHandlerInterface instance,
HttpResponse response) {
// TODO Auto-generated method stub
}
#Override
public void setTag(Object TAG) {
// TODO Auto-generated method stub
}
#Override
public Object getTag() {
// TODO Auto-generated method stub
return null;
}
};
/**
* Cancel upload by calling this method
*/
public void cancel() throws Exception {
AsynchConfig.mClient.cancelAllRequests(true);
handle.cancel(true);
}
}
Asynch config class
public final class AsynchConfig {
public static AsyncHttpClient mClient = new AsyncHttpClient();
}
Use
RequestParams params = new RequestParams();
params.put("fileTitle","MyFile1");
params.put("file", new File("File Path Here")); // e.g Environment.getExternalStorageDirectory().getPath() + "/test.mp3"
AsyncLoader asyncUploader = new AsyncLoader(this, "URL_HERE", params, callHandler);
asyncUploader.startTransfer();
CallHandler Interface object
LoaderCallBackHandler callHandler = new LoaderCallBackHandler() {
#Override
public void uploadComplete(String response) {
// TODO Auto-generated method stub
}
#Override
public void progressUpdate(long bytesWritten, long bytesTotal) {
// TODO Auto-generated method stub
}
#Override
public void onStartUploading() {
// TODO Auto-generated method stub
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
}
#Override
public void onCancle() {
// TODO Auto-generated method stub
}
#Override
public void failedWithError(Throwable error) {
// TODO Auto-generated method stub
}
};
PHP service for handling uploaded file
if(isset($_FILES['file']) && isset($_POST['fileTitle']) ) {
include './config.php';
//Randomly genrate file name
$stickerTmp = explode(".", $_FILES["file"]["name"]);
$file = md5(date("l, F d, Y h:i" ,time()) . (microtime())).".".end($stickerTmp);
//geting the temp location of file
$filetemploc=$_FILES['file']['tmp_name'];
//path for uploading to the specific location
$pathandname="file_store/".$file;
// moving the file to specified path
$resultUpload = move_uploaded_file($filetemploc, $pathandname);
// if file is successfully moved to over specified path then insert the reference into the DB
if($resultUpload == TRUE) {
//echo "File has been moved from : ". $filetemploc . " to :".$pathandname;
$qInsert = "INSERT INTO file_lists values (null,'".$_POST['fileTitle']."','".$file."') ";
mysql_query($qInsert);
}
}
Related
I have a navigation drawer containing 2 items. Now in my first item click, I load data using asynctask and the loaded data is populated in a listview in the corresponding fragment. Now when I switch to 2nd item, again I load data using AsyncTask for the 2nd fragment and show it in in listview.
Now the problem starts. When I go back to the 1st fragment, my
asyncTask is called again and the data is again fetched from the
server, I want to prevent this and load my data directly if it has
been already loaded once.
Please suggest
P.S - Please ask for the code if anyone needs it.
USERPAYFRAGMENT
public class UserPay extends Fragment {
ProgressDialog prg;
Properties prop;
private PrefSingleton mMyPreferences;
private JSONParser jsonParser = new JSONParser();
ArrayList<HashMap<String, String>> RequestList;
HashMap<String, String> map;
UserAdapter req_adp;
ListView req;
private boolean flag;
#Override
public void onAttach(Activity activity) {
// TODO Auto-generated method stub
super.onAttach(activity);
Toast.makeText(getActivity(), "ATTACHED", 1000).show();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
Toast.makeText(getActivity(), "CREATE", 1000).show();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.user_pay, container, false);
initViews(rootView);
Toast.makeText(getActivity(), "ONCREATEVIEW", 1000).show();
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Toast.makeText(getActivity(), "ONACTIVITYCREATED", 1000).show();
mMyPreferences = PrefSingleton.getInstance();
mMyPreferences.Initialize(getActivity());
RequestList = new ArrayList<HashMap<String, String>>();
Resources resources = this.getResources();
AssetManager assetManager = resources.getAssets();
try {
InputStream inputStream = assetManager.open("jsonURL.properties");
prop = new Properties();
prop.load(inputStream);
} catch (IOException e) {
System.err.println("Failed to open jsonURL property file");
e.printStackTrace();
}
req_adp = new UserAdapter(getActivity(), RequestList);
req.setAdapter(req_adp);
if (!flag) {
new GetRequests().execute();
} else {
}
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
Toast.makeText(getActivity(), "ONSTART", 1000).show();
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
Toast.makeText(getActivity(), "ONRESUME", 1000).show();
}
private void initViews(View v) {
req = (ListView) v.findViewById(R.id.req_list);
}
private class GetRequests extends AsyncTask<Void, Void, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
prg = new ProgressDialog(getActivity());
prg.setIndeterminate(true);
prg.setMessage("Fetching Pending Requests...");
prg.setCanceledOnTouchOutside(false);
prg.show();
}
#Override
protected Integer doInBackground(Void... params) {
List<NameValuePair> params1 = new ArrayList<NameValuePair>();
params1.add(new BasicNameValuePair("userID", mMyPreferences
.getPreference("LoginId")));
String error_code = null;
Log.e("URL ", "is" + prop.getProperty("GET_REQUESTS_URL"));
try {
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(
Appconstant.GET_REQUESTS_URL, "POST", params1);
// Check your log cat for JSON response
Log.d("Inbox JSON: ", json.toString());
JSONObject jsonObj = json.getJSONObject("data");
error_code = jsonObj.getString("Error_Code");
RequestList.clear();
if ("1".equals(error_code)) {
JSONArray jArray = jsonObj.getJSONArray("result");
for (int i = 0; i < jArray.length(); i++) {
map = new HashMap<String, String>();
JSONObject jsonObj1 = jArray.getJSONObject(i);
String FBankId = jsonObj1
.getString("payment_from_bank_id");
String DestBankId = jsonObj1
.getString("payment_to_bank_id");
String FBank = jsonObj1.getString("fBank");
String TBank = jsonObj1.getString("tBank");
String reason = jsonObj1.getString("payment_reason");
String amt = jsonObj1.getString("amount");
String p_type = jsonObj1.getString("payment_type");
String status = jsonObj1.getString("status");
String r_date = jsonObj1
.getString("request_created_date");
map.put("FBankId", FBankId);
map.put("TBankId", DestBankId);
map.put("SourceBank", FBank);
map.put("DestBank", TBank);
map.put("ReqDate", r_date);
map.put("PayReason", reason);
map.put("Amt", amt);
map.put("PayType", p_type);
map.put("Status", status);
if (status.equals("pending")) {
if (p_type.equals("cheque")
|| p_type.equals("Net Banking")) {
RequestList.add(map);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return Integer.parseInt(error_code);
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
if (prg.isShowing()) {
prg.cancel();
}
if (result == 2) {
Toast.makeText(getActivity(),
"No User Request Details Available.Please Try Again",
Toast.LENGTH_SHORT).show();
}
req_adp.notifyDataSetChanged();
flag = true;
}
}
#Override
public void onPause() {
// TODO Auto-generated method stub
super.onPause();
Toast.makeText(getActivity(), "ONPAUSE",1000).show();
}
#Override
public void onStop() {
// TODO Auto-generated method stub
super.onStop();
Toast.makeText(getActivity(), "ONSTOP", 1000).show();
}
#Override
public void onDestroyView() {
// TODO Auto-generated method stub
super.onDestroyView();
Toast.makeText(getActivity(), "ONDESTROYVIEW", 1000).show();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(getActivity(), "ONDESTROY", 1000).show();
}
#Override
public void onDetach() {
// TODO Auto-generated method stub
super.onDetach();
Toast.makeText(getActivity(), "ONDETACH", 1000).show();
}
}
There are 2 ways to solve
1 - store the data locally and make use stored data based on appropriate condition checks
2 - If your app is based on this 2 fragments, just create the instance of these fragments and store in in member variable of parent activity. do not give chance to recreate again and again
I have that AsyncTask code
public class DiceTask extends AsyncTask<Socket, Void, int[]> {
private int[] arrayFromServer = new int[8];
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected int[] doInBackground(Socket...params) {
Socket soc = params[0];
try {
ObjectInputStream ois = new ObjectInputStream(soc.getInputStream());
int[] tempArray = (int[]) (ois.readObject());
return tempArray;
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
#Override
protected void onProgressUpdate(Void...arg1) {
}
#Override
protected void onPostExecute(int[] result) {
arrayFromServer = result;
}
public int[] getTempDice() {
return arrayFromServer;
}
}
where is called this way into my main thread.
rollDiceButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rollDiceButton.setEnabled(false);
rollDice();
task.execute(socket);
tempArray = task.getTempDice();
printDice(tempArray,pDice);
clickableDice(pDice);
}
});
where I am getting a null tempArray. If I change my onPreExecute to this
#Override
protected void onPreExecute() {
super.onPreExecute();
for(int i = 0; i < arrayFromServer.length; i++) {
arrayFromServer[i] = 1;
}
}
I am getting my dice as it should, all are one. The code I am running into the rollDice() is this
public void rollDice() {
try {
DataOutputStream sout = new DataOutputStream(socket.getOutputStream());
String line = "dice";
PrintStream out = new PrintStream(sout);
out.println(line);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
and I can see the results in the server.
You don't need to implement onPostExecute in your AsyncTask class definition. You also don't need the getTempDice function. You just need to override onPostExecute in an anonymous class and run your UI code in it.
rollDiceButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rollDiceButton.setEnabled(false);
rollDice();
task = new DiceTask() {
#Override
public void onPostExecute(int[] result) {
tempArray = result;
printDice(tempArray,pDice);
clickableDice(pDice);
}
}.execute(socket);
}
});
Children of AsyncTask run in parallel with main Thread, you are trying access the attribute arrayFromServer right after to start the Thread. It's recommended you use a callback to retried the value wanted, making sure you get the value after Thread is done.
Making the follow changes can solve your problem. Let me know if you understand.
public class DiceTask extends AsyncTask<Socket, Void, int[]> {
public interface Callback {
void onDone(int[] arrayFromServer);
}
private Callback mCallback;
public DiceTask(Callback c) {
mCallback = c;
}
#Override
protected int[] doInBackground(Socket...params) {
Socket soc = params[0];
try {
ObjectInputStream ois = new ObjectInputStream(soc.getInputStream());
int[] tempArray = (int[]) (ois.readObject());
return tempArray;
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(int[] result) {
mCallback.onDone(result);
}
}
rollDiceButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rollDiceButton.setEnabled(false);
rollDice();
new DiceTask(new Callback() {
public void onDone(int[] tempArray) {
printDice(tempArray,pDice);
clickableDice(pDice);
}
}).execute(socket);
}
});
I am trying to get the result from the AsyncTask to another class. I am using interface to achieve this. I doing the same procedure in another module and it was working good but I fail to identify the issue in this case...
I'm calling like this from another class.
GroupDetails gd=new GroupDetails();
groups=gd.getGroupList("email");
public class GroupDetails implements AsyncResponse {
String result;
String[] groupList;
public String getGroupList(String userEmail){
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("user_email", userEmail));
PhpConnect phpcon=new PhpConnect("http://www.pinnacle2k14.com/letsmeet/get_group.php",postParameters);
phpcon.delegate=this;
phpcon.execute();
result="hello"
return result;
}
#Override
public void processFinish(String output) { //this method not functioning why?
// TODO Auto-generated method stub
result="hello";
//groupList=output.split(",");
}
}
PhpConnect.php
public class PhpConnect extends AsyncTask<String, Void, String> {
String url1;
ArrayList<NameValuePair> postParameters1;
public PhpConnect(String url,ArrayList<NameValuePair> postParameters){
url1=url;
postParameters1=postParameters;
}
public PhpConnect() {
// TODO Auto-generated constructor stub
}
String response;
public AsyncResponse delegate=null;
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
response = CustomHttpClient.executeHttpPost(url1,postParameters1);
} catch (Exception e) {
// TODO Auto-generated catch block
response=e.toString();
}
return response;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
delegate.processFinish(result);
}
}
AsynResponse interface
public interface AsyncResponse {
void processFinish(String output);
}
You know you can do
PhpConnect phpcon=new PhpConnect("http://www.pinnacle2k14.com/letsmeet/get_group.php",postParameters) {
#Override
public void onPostExecute(String result) {
//DO YOUR STUFF
}
};
phpcon.execute();
This way you can save the callback.
I am working on an application that requires data to be displayed on a listview. The data to be displayed on the listview needs to be updated frequently so i created a sync-adapter which will be triggered my a broadcast message from gcm. When this occurs my AsyncTask loader.onContentChanged is called which call the loadinbackground method and all this works properly. The issues i am having is displaying the new data on the listview without restarting the activity. i am trying to get it to work like facebook news feed listview.
Please help me
My codes are as follows
SyncAdapter
#Override
public void onPerformSync(Account account, Bundle extras, String authority,
ContentProviderClient provider, SyncResult syncResult) {
// TODO Auto-generated method stub
Log.d(TAG, "onPerformSync for account[" + account.name + "]");
String theValue = mAccountManager.getUserData(account, "User_ID");
mContentResolver = mContext.getContentResolver();
final RoomListLoader mLoader = new RoomListLoader(mContext, theValue);
mLoader.onContentChanged();
}
Loader
public class RoomListLoader extends AsyncTaskLoader<List<RoomList>> {
private static String url = "********************";
int success;
private static final String TAG_SUCCESS = "success";
private static final String TAG_ROOMS = "room";
String room_id = null, roomTitle, created_at, user_id, room_ids,
clickedOnRoomId, retrievedRoomId, username;
String room_title, reward, numOfComments, filePath;
JSONParser jsonParser = new JSONParser();
JSONObject json;
JSONArray rooms = null;
JSONArray ids = null;
int i = 0, c = 0, tryme = 0, tryme2 = 0;
int co = 0, counterOnGetRooms = 0;
RoomList details;
public static List<RoomList> mRoomList = new ArrayList<RoomList>();
Context mContext;
//private final Handler observerHandler;
public RoomListLoader(Context context,String nuser_id) {
super(context);
// TODO Auto-generated constructor stub
//mRoomList = nRoomList;
this.user_id = nuser_id;
this.mContext = context;
//observerHandler = new Handler();
}
#Override
public List<RoomList> loadInBackground() {
// TODO Auto-generated method stub
mRoomList.clear();
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user_id", user_id));
json = jsonParser.makeHttpRequest(url, "POST", params);
// final Context context = getContext();
try {
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
rooms = json.getJSONArray(TAG_ROOMS);
// counter = json.getInt("counter");
counterOnGetRooms = json.getInt("count");
Log.d("counterOnGetRooms", "" + counterOnGetRooms);
// Log.v("counter", "" + counter);
for (int i = 0; i < rooms.length(); i++) {
tryme2++;
JSONObject c = rooms.getJSONObject(i);
// get room titles
roomTitle = c.getString("room_title");
retrievedRoomId = c.getString("room_id");
created_at = c.getString("created_at");
username = c.getString("username");
numOfComments = c.getString("counters");
filePath = c.getString("filePath");
Log.i("filePath", filePath);
details = new RoomList(retrievedRoomId, roomTitle,
created_at, username, numOfComments, filePath);
mRoomList.add(details);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//MostRecentRooms Room;
//deliverResult(mRoomList);
return mRoomList;
}
#Override
public void onContentChanged() {
// TODO Auto-generated method stub
super.onContentChanged();
loadInBackground();
//deliverResult(mRoomList);
}
#Override
public void onCanceled(List<RoomList> data) {
// TODO Auto-generated method stub
super.onCanceled(data);
}
#Override
public void deliverResult(List<RoomList> data) {
// TODO Auto-generated method stub
Log.d("Deliver Result",""+data.size());
super.deliverResult(data);
}
#Override
protected void onReset() {
// TODO Auto-generated method stub
super.onReset();
onStopLoading();
}
#Override
protected void onStartLoading() {
// TODO Auto-generated method stub
if (mRoomList != null) {
//deliverResult(mRoomList);
}
super.onStartLoading();
}
#Override
protected void onStopLoading() {
// TODO Auto-generated method stub
cancelLoad();
}
}
Activity
public class MostRecentRooms extends ListActivity implements LoaderManager.LoaderCallbacks<List<RoomList>> {
// progress dialog
ProgressDialog pDialog;
// json parser object
JSONParser jsonParser = new JSONParser();
int decrement = 0;
int success;
int s = 0;
Activity mActivity;
// url to view most recent rooms
private static String url = "************8";
// url to load more rooms
private static String url3 = "***************";
// url to check status of user
private static String url2 = "*****************";
// url to get profile images
private static String url4 = "****************88";
private static final String TAG_SUCCESS = "success";
private static final String TAG_ROOMS = "room";
int Loader_ID =0x3;
int counter = 0;
HashMap<String, String> map;
public static List<RoomList> mRoomList = new ArrayList<RoomList>();
RoomList details;
ListAdapter adapter;
public static RoomListAdapter mAdapter;
public static LoaderManager mLoadManager;
// json arrays
JSONArray rooms = null;
JSONArray ids = null;
int i = 0, c = 0, tryme = 0, tryme2 = 0;
int co = 0, counterOnGetRooms = 0;
// Array list to hold room titles
ArrayList<HashMap<String, String>> allRooms;
// ArrayList<String> allRooms;
// List view to show room titles of an arraylist
public ListView lv;
// json Object
JSONObject json;
int limit = 20;
// strings
String room_id = null, roomTitle, created_at, user_id, room_ids,
clickedOnRoomId, retrievedRoomId, username;
String room_title, reward, numOfComments, filePath;
// buttons
Button back, loadMore, refresh;
Bitmap img_bitmap;
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_most_recent_rooms);
mLoadManager = getLoaderManager();
mAdapter = new RoomListAdapter(this, getApplicationContext());
lv= getListView();
lv.setAdapter(mAdapter);
// back button
back = (Button) findViewById(R.id.backToMainMenu);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
// end back button
// get user id from View rooms class
if (getIntent().getExtras().getString("user_id_value") != null)
user_id = getIntent().getExtras().getString("user_id_value");
else
Log.e("Error", "Missing user_id");
mLoadManager.initLoader(Loader_ID,null,MostRecentRooms.this);
//allRooms = new ArrayList<HashMap<String, String>>();
// allRooms = new ArrayList<String>();
// call class GetAllRooms
//new GetAllRooms().execute();
// get room_id
if (getIntent().getExtras().getString("room_id_to_send") != null)
room_id = getIntent().getExtras().getString("room_id_to_send");
else
Log.e("Error", "Missing room id");
loadMore = (Button) findViewById(R.id.loadMore);
loadMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//new LoadMoreRooms().execute();
// counter -= 5;
}
});
refresh = (Button) findViewById(R.id.refresh);
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mRoomList.clear();
allRooms.clear();
limit = 20;
tryme = 0;
img_bitmap.recycle();
//new GetAllRooms().execute();
}
});
}
/**
* This class get users status whether deleted or not
*/
class GetUserStatus extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
backGroundProcess(user_id);
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.e("i is", "" + i);
if (i == 2) {
// decativatedPage();
Toast.makeText(getApplicationContext(), "noooo",
Toast.LENGTH_SHORT).show();
} else {
Intent i = new Intent(getApplicationContext(), RoomPage.class);
i.putExtra("room_id_to_send", clickedOnRoomId);
i.putExtra("user_id_value", user_id);
startActivity(i);
}
}
}// end class
private void backGroundProcess(String string) {
// build parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user_id", string));
json = jsonParser.makeHttpRequest(url2, "POST", params);
int success;
try {
success = json.getInt("success");
if (success == 1) {
i = 1;
Log.i("status", json.getString("message").toString());
} else if (success == 2) {
i = 2;
} else {
Log.d("Error", "Something went wrong");
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public Loader<List<RoomList>> onCreateLoader(int id, Bundle args) {
// TODO Auto-generated method stub
Log.d("Tsg", "here");
RoomListLoader mRoomloader = new RoomListLoader(getApplicationContext(), user_id);
mRoomloader.forceLoad();
return mRoomloader ;
}
#Override
public void onLoadFinished(Loader<List<RoomList>> arg0, List<RoomList> data) {
// TODO Auto-generated method stub
Log.i("tag","list loaded");
if(data != null){
mAdapter.SetData(data);
mAdapter.notifyDataSetChanged();
}
//mAdapter.SetData(data);
Log.i("Tag",""+data.size());
//lv.setAdapter(mAdapter);
}
#Override
public void onLoaderReset(Loader<List<RoomList>> arg0) {
// TODO Auto-generated method stub
Log.d("Loader", "Loader Reset");
mAdapter.SetData(null);
}
}
Adapter
public class RoomListAdapter extends ArrayAdapter<RoomList> {
ImageLoader imageLoader = null;
private Activity activity;
String TAG = "RoomListAdapter";
private final LayoutInflater mInflator;
List<RoomList> nRoomList;
public RoomListAdapter(Activity a, Context context) {
// TODO Auto-generated constructor stub
super(context, R.layout.viewroom_layout);
activity = a;
mInflator = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(a.getApplicationContext());
//nRoomList = mRoomList;
//SetData(nRoomList);
}
public void SetData(List<RoomList> data) {
clear();
if (data != null) {
addAll(data);
}
}
#Override
public void notifyDataSetChanged() {
// TODO Auto-generated method stub
super.notifyDataSetChanged();
}
#Override
public void setNotifyOnChange(boolean notifyOnChange) {
// TODO Auto-generated method stub
super.setNotifyOnChange(notifyOnChange);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi;
if (convertView == null) {
vi = mInflator.inflate(R.layout.viewroom_layout, null);
} else {
vi = convertView;
}
TextView room_id = (TextView) vi.findViewById(R.id.roomsIDHidden);
TextView room_title = (TextView) vi.findViewById(R.id.roomsName);
TextView created_at = (TextView) vi.findViewById(R.id.createdTime);
TextView username = (TextView) vi.findViewById(R.id.creatorName);
TextView numOfComments = (TextView) vi.findViewById(R.id.numComments);
ImageView image = (ImageView) vi.findViewById(R.id.userPic);
//Log.d(TAG, "Within the room list adapter");
RoomList info = getItem(position);
room_id.setText(info.getmRoom_id());
room_title.setText(info.getmRoomTitle());
created_at.setText(info.getmCreated_at());
username.setText(info.getmUsername());
numOfComments.setText(info.getmNumberOfComments());
imageLoader.DisplayImage(info.getmFilePath(), image);
return vi;
}
}
with the help of venkat and monica i solved it didn't need the Syncadpter all i needed was a broadcast receiver this i did by
1) creating a broad cast intent when GCM receives the message
Intent intent1 = new Intent();
intent1.setAction("com.gcm.updatecame");
this.sendBroadcast(intent1);
2) in my Activity i register the receiver and create the class
filter1= new IntentFilter("com.gcm.updatecame");
registerReceiver(myReceiver, filter1);
Broadcast Receiver
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// write your code here to update the listview.
if(mLoadManager != null){
Reload.setVisibility(View.VISIBLE);
Reload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mLoadManager.destroyLoader(Loader_ID);
mAdapter.notifyDataSetChanged();
mAdapter.SetData(null);
mRoomList.clear();
mLoadManager.initLoader(Loader_ID, null, MostRecentRooms.this);
Reload.setVisibility(View.INVISIBLE);
}
});
}
}
};
Replace you onLoadFinished method with this one:
#Override
public void onLoadFinished(Loader<List<RoomList>> arg0, List<RoomList> data) {
if(data != null){
mAdapter = new RoomListAdapter(this, getApplicationContext());
mAdapter.SetData(data);
lv.setAdapter(mAdapter);
}
}
I am planning to use MVP pattern for my new Android project. I have done some sample code and I would like to know, have I implemented it correctly? Please give comments on the code and also post your suggestions.
my activity class I am extending it from my BaseView class and I am implementing an interface. this activity simply calls an webservice in a new thread and updates the value in the textview.
public class CougarTestView extends BaseView implements ICougarView,
OnClickListener {
CougarTestPresenter _presenter;
public String activityName = "CougarHome";
/** Called when the activity is first created. */`enter code here`
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState, activityName);
setContentView(R.layout.main);
_presenter = new CougarTestPresenter(this);
getSubmitBtn().setOnClickListener(this);
getCallInfoBtn().setOnClickListener(this);
}
private Button getCallInfoBtn() {
return (Button) findViewById(R.id.btn_callinfo);
}
public void setServiceValue(String retVal) {
// TODO Auto-generated method stub
getResultLabel().setText(retVal);
setPbar(false);
// toastMsg(retVal);
}
public void ResetPbar() {
getProgressBtn().setProgress(0);
}
public void setProcessProgress(int progress) {
if (getProgressBtn().getProgress() < 100) {
getProgressBtn().incrementProgressBy(progress);
} else {
setPbar(false);
}
}
private TextView getResultLabel() {
return (TextView) findViewById(R.id.result);
}
private Button getSubmitBtn() {
return (Button) findViewById(R.id.btn_triptype);
}
private ProgressBar getProgressBtn() {
return (ProgressBar) findViewById(R.id.pgs_br);
}
public void setPbar(boolean visible) {
if (!visible) {
getProgressBtn().setVisibility(View.GONE);
} else
getProgressBtn().setVisibility(View.VISIBLE);
}
#Override
public void setHttpResult(String retVal) {
// TODO Auto-generated method stub
setServiceValue(retVal);
}
private void toastMsg(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn_triptype: {
try {
_presenter.valueFromService(RequestType.CallInfo, 0);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
default:
setServiceValue("default");
}
}
}
My activity class: in my activity class i am having a textview and a button. when i press the button , it call the webservice to get the data in the presenter class. the presenter class calls the webservice parses the response and sets the value in the textview of the activity.
My presenter class
public class CougarTestPresenter {
ICougarView mIci;
RequestType mRtype;
public String result= "thisi s result i";
Handler mHandle;
public CougarTestPresenter(ICougarView ici) {
mIci = ici;
}
public void valueFromService(RequestType type, int x) throws Exception{
String url = getURLByType(type);
// GetServiceresult service = new GetServiceresult();
// service.execute(url);
Handler handle = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case Globals.IO_EXPECTION: {
Toast.makeText(mIci.getContext(), msg.toString(),
Toast.LENGTH_LONG).show();
NetworkConnectivityListener connectivityListener = NetworkConnectivityListener
.getInstace();
mHandle = CustomHandler.getInstance(mIci.getContext(),
connectivityListener, mIci);
connectivityListener.registerHandler(mHandle,
Globals.CONNECTIVITY_MSG);
connectivityListener.startListening(mIci.getContext());
mIci.setPbar(false);
}
break;
case Globals.RHAPSODY_EXCEPTION:{
ExceptionInfo exInfo =null;
try {
exInfo = Utility.ParseExceptionData(msg.obj.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mIci.setServiceValue(exInfo.Message + exInfo.Type +exInfo.Detail);
// new HandleRhapsodyException(mIsa, exInfo);
}
break;
default: {
Toast.makeText(mIci.getContext(), msg.toString(),
Toast.LENGTH_LONG).show();
mIci.setServiceValue(msg.obj.toString());
}
}
}
};
ServiceResult thread = new ServiceResult(handle, url);
mIci.setPbar(true);
thread.start();
}
public String getURLByType(RequestType type) {
// TODO Auto-generated method stub
switch (type) {
case CallInfo: {
return ("www.gmail.com");
}
case TripType: {
return ("www.google.com");
}
default:
return ("www.cnet.com");
}
}
private class ServiceResult extends Thread {
Handler handle;
String url;
public ServiceResult(Handler handle, String url) {
this.handle = handle;
this.url = url;
}
public void run() {
sendExceptionLog(handle);
}
}
public void sendExceptionLog(Handler handle) {
DebugHttpClient httpClient = new DebugHttpClient();
HttpGet get = new HttpGet(
"https://192.168.194.141/TripService/service1/");
try {
HttpResponse response = httpClient.execute(get);
HttpEntity r_entity = response.getEntity();
String xmlString = EntityUtils.toString(r_entity);
// setdvrid.setText(xmlString + " "
// + response.getStatusLine().getStatusCode());
httpClient.getConnectionManager().shutdown();
if (response.getStatusLine().getStatusCode() != 200) {
handle.sendMessage(Message.obtain(handle, Globals.RHAPSODY_EXCEPTION,
xmlString));
result= Utility.ParseExceptionData(xmlString).Message;
}
else
{
handle.sendMessage(Message.obtain(handle, Globals.SERVICE_REPONSE,
response.getStatusLine().getStatusCode()
+ response.getStatusLine().getReasonPhrase()
+ xmlString));
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
handle.sendMessage(Message.obtain(handle, Globals.OTHER_EXPECTION,
e.getMessage().toString() + "she"));
} catch (IOException e) {
// TODO Auto-generated catch block
handle.sendMessage(Message.obtain(handle, Globals.IO_EXPECTION, e
.getMessage().toString() + "he"));
} catch (Exception e) {
handle.sendMessage(Message.obtain(handle, Globals.OTHER_EXPECTION,
e.getMessage().toString() + "it"));
}
}
the below interface is implemented in the activity class and the instance of the activity class is sent as interface object to the constructor of the presenter class.
my view interface
public interface ICougarView {
public void setServiceValue(String retVal);
public void setProcessProgress(int progress);
public void setPbar(boolean b);
public void ResetPbar();
public Context getContext();
}
Sorry for the late :)
I've use MVP on Android this way.
Activities are presenters. Every presenter has a link to model(s) (sometimes it is services, sometimes not, depending from the task) and to view(s). I create custom view and set it as the content view for activity.
See:
public class ExampleModel {
private ExampleActivity presenter;
public ExampleModel(ExampleActivity presenter) {
this.presenter = presenter;
}
//domain logic and so on
}
public class ExampleActivity extends Activity {
private ExampleModel model;
private ExampleView view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
model = new ExampleModel(this);
view = new ExampleView(this);
setContentView(view);
}
// different presenter methods
}
public class ExampleView extends LinearLayout {
public ExampleView(Context context) {
super(context);
}
}
Also, I've discussed this topic here.
I should warn you, that Activity shouldn't be considered as the view. We had very bad expirience with it, when we wrote with PureMVC which considered Activity as view component. Activity is excellently suitable for controller/presenter/view model (I've tried all of them, I like MVP the most), it has excellent instrumentation for managing the views (View, Dialog and so on) while it's not a view itself.